Skip to content

Commit 672a39e

Browse files
committed
Add timeout when waiting for avatar file to be created or modified
1 parent acc3aa4 commit 672a39e

1 file changed

Lines changed: 16 additions & 9 deletions

File tree

Site/src/routes/api/avatar/[username]/+server.ts

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import fs from "node:fs"
22
import { error } from "@sveltejs/kit"
33
import { db, type RecordId } from "$lib/server/surreal"
44

5+
const timeout = 10 // seconds
6+
57
export async function GET({ params, url }) {
68
let { username } = params
79
if (!username) error(400, "Invalid Request")
@@ -26,16 +28,21 @@ export async function GET({ params, url }) {
2628
if (wait)
2729
// If the file doesn't exist, wait for it to be created
2830
// if it does exist, wait for it to be modified
29-
await new Promise<void>(resolve => {
30-
try {
31-
const watcher = fs.watch(path, () => {
32-
watcher.close()
31+
32+
await Promise.race([
33+
new Promise<void>(resolve => {
34+
try {
35+
const watcher = fs.watch(path, () => {
36+
watcher.close()
37+
resolve()
38+
})
39+
} catch {
3340
resolve()
34-
})
35-
} catch {
36-
resolve()
37-
}
38-
})
41+
}
42+
}),
43+
// ...but don't wait forever
44+
new Promise(resolve => setTimeout(resolve, timeout * 1000)),
45+
])
3946
else if (!(await Bun.file(path).exists()))
4047
throw new Error("File does not exist")
4148

0 commit comments

Comments
 (0)