Skip to content

Instantly share code, notes, and snippets.

@oahehc
Created September 30, 2020 03:41
Show Gist options
  • Save oahehc/253282f0984ade0437708de63f7569ec to your computer and use it in GitHub Desktop.
Save oahehc/253282f0984ade0437708de63f7569ec to your computer and use it in GitHub Desktop.
self.addEventListener("fetch", (event) => {
// hijacking path and return a mock HTML content
if (event.request.url.includes("/faq")) {
event.respondWith(
new Response("<div>Mock FAQ Page</div>", {
headers: { "Content-Type": "text/html" },
})
);
}
// hijacking API request and return mock response in JSON format
if (event.request.url.includes("/api/users")) {
const data = [
{
id: "0001",
name: "andrew",
},
];
const blob = new Blob(
[JSON.stringify(data, null, 2)],
{ type: "application/json" }
);
const init = { status: 200, statusText: "default mock response" };
const defaultResponse = new Response(blob, init);
event.respondWith(defaultResponse);
}
// Stale-while-revalidate:
// return the cached version if it exists. At the same time,
// send a request to get the latest version and update the cache
const requestUrl = new URL(event.request.url);
if (requestUrl.pathname.startsWith("/avatars/")) {
const response = caches.open(CACHE_NAME).then((cache) => {
return cache.match(event.request).then((response) => {
const networkFetch = fetch(event.request)
.then((networkResponse) => {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
return response || networkFetch;
});
});
event.respondWith(response);
return;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment