Skip to content

Commit

Permalink
feat: update fetch to fire an asynchronous update cache job
Browse files Browse the repository at this point in the history
  • Loading branch information
zugdev committed Oct 31, 2024
1 parent c459465 commit 363dcd7
Show file tree
Hide file tree
Showing 2 changed files with 8,349 additions and 5,862 deletions.
61 changes: 34 additions & 27 deletions static/progressive-web-app.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,36 +64,43 @@ self.addEventListener("fetch", (event) => {

event.respondWith(
(async () => {
try {
const cachedResponse = await caches.match(event.request);
const cachedResponse = await caches.match(event.request);

const fetchPromise = fetch(event.request)
.then(async (networkResponse) => {
if (networkResponse.ok) {
const responseClone = networkResponse.clone();
const cache = await caches.open(cacheName);
await cache.put(event.request, responseClone);
if (cachedResponse) {
// Start a network fetch in the background to update the cache, this will return early from cache
// but the fetch will still happen in the background
event.waitUntil(
(async () => {
try {
const networkResponse = await fetch(event.request);
if (networkResponse.ok) {
const responseClone = networkResponse.clone();
const cache = await caches.open(cacheName);
await cache.put(event.request, responseClone);
}
} catch (error) {
console.error("[Service Worker] Background cache update failed:", error);
}
return networkResponse;
})
.catch((error) => {
console.error("[Service Worker] Network request failed:", error);
return (
cachedResponse ||
new Response("Offline content unavailable", {
status: 503,
statusText: "Service Unavailable",
})
);
})()
);
return cachedResponse;
} else {
// Attempt to fetch from the network if no cache is available
try {
const networkResponse = await fetch(event.request);
if (networkResponse.ok) {
const responseClone = networkResponse.clone();
const cache = await caches.open(cacheName);
await cache.put(event.request, responseClone);
}
return networkResponse;
} catch (error) {
console.error("[Service Worker] Fetch failed, and no cache is available:", error);
return new Response("An error occurred", {
status: 500,
statusText: "Internal Server Error",
});

return cachedResponse || (await fetchPromise);
} catch (error) {
console.error("[Service Worker] Error handling fetch:", error);
return new Response("An error occurred", {
status: 500,
statusText: "Internal Server Error",
});
}
}
})()
);
Expand Down
Loading

0 comments on commit 363dcd7

Please sign in to comment.