Skip to content

Commit e5163bf

Browse files
committed
fix: file preview cache
1 parent 8967d88 commit e5163bf

File tree

2 files changed

+23
-14
lines changed

2 files changed

+23
-14
lines changed

src/server/api/routes/file.ts

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,38 +11,44 @@ const app = new Hono<Env>()
1111
const user = c.var.user!;
1212
const fileId = c.req.param("id");
1313

14-
const etag = btoa(`"${user.id}-${fileId}"`);
15-
c.header("ETag", etag);
16-
if (c.req.header("If-None-Match") === etag) {
17-
return new Response(null, {
18-
status: 304,
19-
statusText: "Not Modified",
20-
});
21-
}
22-
2314
const metadata = await getFileMetadata(fileId, user.id);
2415
if (!metadata) {
2516
return c.json({ error: "File not found" }, 404);
2617
}
2718

19+
// Determine content type based on protocol
20+
let contentType = "image/png";
21+
if (metadata.protocol === "data:") {
22+
const base64Header = metadata.accessUrl.split(",")[0];
23+
contentType = base64Header?.split(";")[0]?.split(":")[1] || "image/png";
24+
} else if (metadata.protocol === "file:") {
25+
const suffix = metadata.accessUrl.split(".").pop();
26+
contentType = `image/${suffix}`;
27+
}
28+
29+
// Set ETag and check cache
30+
const etag = btoa(`"${user.id}-${fileId}"`);
31+
c.header("ETag", etag);
32+
c.header("Content-Type", contentType);
33+
c.header("Cache-Control", "private, max-age=31536000");
34+
35+
if (c.req.header("If-None-Match") === etag) {
36+
return c.body(null, 304);
37+
}
38+
2839
switch (metadata.protocol) {
2940
case "data:": {
3041
const [base64Header, base64Data] = metadata.accessUrl.split(",");
3142
if (!base64Header || !base64Data) {
3243
return c.json({ error: "Invalid file data" }, 500);
3344
}
34-
// Set the content type based on the header
35-
const contentType = base64Header.split(";")[0]?.split(":")[1] || "image/png";
36-
c.header("Content-Type", contentType);
3745
return stream(c, async (stream) => {
3846
const buffer = Buffer.from(base64Data, "base64");
3947
await stream.write(buffer);
4048
});
4149
}
4250
case "file:": {
43-
const suffix = metadata.accessUrl.split(".").pop();
4451
const fileBuffer = await fs.readFile(metadata.accessUrl);
45-
c.header("Content-Type", `image/${suffix}`);
4652
return stream(c, async (stream) => {
4753
await stream.write(fileBuffer);
4854
});

wrangler.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ main = "src/server/worker.ts"
44
compatibility_flags = ["nodejs_compat"]
55
compatibility_date = "2025-05-25"
66

7+
[limits]
8+
cpu_ms = 120000 # 2 minutes
9+
710
[assets]
811
directory = "dist"
912
not_found_handling = "single-page-application"

0 commit comments

Comments
 (0)