Last active
November 4, 2023 18:05
-
-
Save tomaustin700/d20f1387f5534a4ede982e013b6b89cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
async fetch(request, env, ctx) { | |
const cacheUrl = new URL(request.url); | |
const response = await fetch(request.url, { method: 'HEAD' }) | |
async function gatherResponse(response) { | |
return response.status; | |
} | |
const result = await gatherResponse(response); | |
if (result != "200") { | |
return new Response("Unauthorised", { status: 401 }); | |
} | |
const urlWithoutQueryParams = request.url.replace(request.search, ''); | |
const cacheKey = new Request(urlWithoutQueryParams, request); | |
const cache = caches.default; | |
let cResponse = await cache.match(cacheKey); | |
if (!cResponse) { | |
console.log( | |
`Response for request url: ${request.url} not present in cache. Fetching and caching request.` | |
); | |
// If not in cache, get it from origin | |
cResponse = await fetch(request); | |
// Must use Response constructor to inherit all of response's fields | |
cResponse = new Response(response.body, response); | |
// Any changes made to the response here will be reflected in the cached value | |
response.headers.append("Cache-Control", "s-maxage=86400"); | |
ctx.waitUntil(cache.put(cacheKey, response.clone())); | |
} else { | |
console.log(`Cache hit for: ${request.url}.`); | |
} | |
return cResponse; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment