|
| 1 | +import { R2Bucket } from "@cloudflare/workers-types"; |
| 2 | +interface Env { |
| 3 | + BUCKET: R2Bucket; |
| 4 | +} |
| 5 | + |
| 6 | +const CORS_HEADERS = { |
| 7 | + "Access-Control-Allow-Origin": "*", |
| 8 | + "Access-Control-Allow-Methods": "GET, PUT, HEAD", |
| 9 | + "Access-Control-Allow-Headers": "*", |
| 10 | +}; |
| 11 | + |
| 12 | +export default { |
| 13 | + async fetch(request: Request, env: Env): Promise<Response> { |
| 14 | + if (request.method === "OPTIONS") { |
| 15 | + return new Response(null, { status: 200, headers: CORS_HEADERS }); |
| 16 | + } |
| 17 | + |
| 18 | + // eslint-disable-next-line no-restricted-globals |
| 19 | + const url = new URL(request.url); |
| 20 | + const key = url.pathname.replace(/^\//, ""); |
| 21 | + |
| 22 | + if (request.method === "HEAD") { |
| 23 | + const obj = await env.BUCKET.head(key); |
| 24 | + if (!obj) return new Response(null, { status: 404, headers: CORS_HEADERS }); |
| 25 | + return new Response(null, { status: 200, headers: { ...CORS_HEADERS, etag: obj.etag } }); |
| 26 | + } |
| 27 | + |
| 28 | + if (request.method === "GET") { |
| 29 | + const obj = await env.BUCKET.get(key); |
| 30 | + if (!obj) return new Response("Not Found", { status: 404, headers: CORS_HEADERS }); |
| 31 | + return new Response(obj.body as never, { |
| 32 | + status: 200, |
| 33 | + headers: { ...CORS_HEADERS, etag: obj.etag, "content-type": obj.httpMetadata?.contentType ?? "application/octet-stream" }, |
| 34 | + }); |
| 35 | + } |
| 36 | + |
| 37 | + if (request.method === "PUT") { |
| 38 | + await env.BUCKET.put(key, request.body as never); |
| 39 | + return new Response(null, { status: 200, headers: CORS_HEADERS }); |
| 40 | + } |
| 41 | + |
| 42 | + return new Response("Method Not Allowed", { status: 405, headers: CORS_HEADERS }); |
| 43 | + }, |
| 44 | +}; |
0 commit comments