From 71c8c7e268550bf73680b5b4d2ec39bb8bfa18aa Mon Sep 17 00:00:00 2001 From: EGOIST Date: Sun, 15 May 2022 01:33:13 +0800 Subject: [PATCH] cache response --- r2/src/index.ts | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/r2/src/index.ts b/r2/src/index.ts index fe6cb35a..c14415d3 100644 --- a/r2/src/index.ts +++ b/r2/src/index.ts @@ -26,10 +26,12 @@ const send = (data: string | Record, init?: ResponseInit) => { } const handler: ExportedHandler<{ BUCKET: R2Bucket; ENCRYPT_SECRET: string }> = { - async fetch(request, env): Promise { + async fetch(request, env, event): Promise { try { // Files are publicly accessible if (request.method === "GET") { + const cache = caches.default + const url = new URL(request.url) if (url.pathname === "/") { @@ -37,11 +39,25 @@ const handler: ExportedHandler<{ BUCKET: R2Bucket; ENCRYPT_SECRET: string }> = { } const key = url.pathname.substring(1) + + const cachedResponse = await cache.match(request) + + if (cachedResponse) { + console.log("cached!") + return cachedResponse + } + const object = await env.BUCKET.get(key) if (!object) { return send("object not found", { status: 404 }) } - return new Response(object.body) + const response = new Response(object.body, { + headers: { + "Cache-Control": "s-maxage=31536000", + }, + }) + event.waitUntil(cache.put(request, response.clone())) + return response } if (request.method === "OPTIONS") { @@ -89,7 +105,12 @@ const handler: ExportedHandler<{ BUCKET: R2Bucket; ENCRYPT_SECRET: string }> = { httpMetadata: { contentType: file.type, }, + customMetadata: { + // Store the original filename + filename: file.name, + }, }) + return send({ key }) } } catch (error: any) {