Skip to content

Instantly share code, notes, and snippets.

@tomaustin700
Last active November 4, 2023 18:05
Show Gist options
  • Save tomaustin700/d20f1387f5534a4ede982e013b6b89cb to your computer and use it in GitHub Desktop.
Save tomaustin700/d20f1387f5534a4ede982e013b6b89cb to your computer and use it in GitHub Desktop.
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