(
request: Request,
env: Env,
ctx: ExecutionContext
)
| 90 | |
| 91 | export default { |
| 92 | async fetch( |
| 93 | request: Request, |
| 94 | env: Env, |
| 95 | ctx: ExecutionContext |
| 96 | ): Promise<Response> { |
| 97 | if (request.method.toUpperCase() === "POST") |
| 98 | return new Response(undefined, { status: 405 }); |
| 99 | |
| 100 | const url = new URL(request.url); |
| 101 | const { ok, name, tile, ext } = tile_path(url.pathname); |
| 102 | |
| 103 | const cache = caches.default; |
| 104 | |
| 105 | if (!ok) { |
| 106 | return new Response("Invalid URL", { status: 404 }); |
| 107 | } |
| 108 | |
| 109 | let allowedOrigin = ""; |
| 110 | if (typeof env.ALLOWED_ORIGINS !== "undefined") { |
| 111 | for (const o of env.ALLOWED_ORIGINS.split(",")) { |
| 112 | if (o === request.headers.get("Origin") || o === "*") { |
| 113 | allowedOrigin = o; |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | const cached = await cache.match(request.url); |
| 119 | if (cached) { |
| 120 | const respHeaders = new Headers(cached.headers); |
| 121 | if (allowedOrigin) |
| 122 | respHeaders.set("Access-Control-Allow-Origin", allowedOrigin); |
| 123 | respHeaders.set("Vary", "Origin"); |
| 124 | |
| 125 | return new Response(cached.body, { |
| 126 | headers: respHeaders, |
| 127 | status: cached.status, |
| 128 | }); |
| 129 | } |
| 130 | |
| 131 | const cacheableResponse = ( |
| 132 | body: ArrayBuffer | string | undefined, |
| 133 | cacheableHeaders: Headers, |
| 134 | status: number |
| 135 | ) => { |
| 136 | cacheableHeaders.set( |
| 137 | "Cache-Control", |
| 138 | env.CACHE_CONTROL || "public, max-age=86400" |
| 139 | ); |
| 140 | |
| 141 | const cacheable = new Response(body, { |
| 142 | headers: cacheableHeaders, |
| 143 | status: status, |
| 144 | }); |
| 145 | |
| 146 | ctx.waitUntil(cache.put(request.url, cacheable)); |
| 147 | |
| 148 | const respHeaders = new Headers(cacheableHeaders); |
| 149 | if (allowedOrigin) |
searching dependent graphs…