Skip to content

Instantly share code, notes, and snippets.

@pakastin
Created December 3, 2024 12:38
Show Gist options
  • Save pakastin/461da5f99c13e5448884724b71a6fb08 to your computer and use it in GitHub Desktop.
Save pakastin/461da5f99c13e5448884724b71a6fb08 to your computer and use it in GitHub Desktop.
const CACHE = "cache_name_here";
self.addEventListener("fetch", (event) => {
const handled = handler(event).then((response) => {
if (!(response instanceof Response)) {
return new Response("Something went wrong", {
status: 500,
});
}
return response;
});
event.respondWith(handled);
});
async function handler(event) {
const { request } = event;
try {
const response = await fetch(request);
if (request?.method !== "GET" || response?.type !== "basic") {
return response;
}
const ok = response?.ok;
if (ok) {
if (response?.status === 200) {
try {
const clonedResponse = response.clone();
const cache = await caches.open(CACHE);
cache.put(request, clonedResponse);
} catch (err) {
console.error(new Error(err));
}
}
return response;
}
throw new Error(`Failed fetching ${request.url}`);
} catch (err) {
return await cachedResponse(request);
}
}
async function cachedResponse(request) {
try {
const cache = await caches.open(CACHE);
const matched = cache.match(request.url);
if (matched) {
return matched;
}
return await fetch(request);
} catch (err) {
console.error(new Error(err));
return new Response("Something went wrong", {
status: 500,
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment