46 lines
1.1 KiB
JavaScript
46 lines
1.1 KiB
JavaScript
const CACHE_NAME = "rave-budget-control-v1";
|
|
const APP_SHELL = ["/", "/login", "/icon.svg", "/manifest.webmanifest"];
|
|
|
|
self.addEventListener("install", (event) => {
|
|
event.waitUntil(
|
|
caches
|
|
.open(CACHE_NAME)
|
|
.then((cache) => cache.addAll(APP_SHELL))
|
|
.then(() => self.skipWaiting())
|
|
);
|
|
});
|
|
|
|
self.addEventListener("activate", (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((cacheNames) =>
|
|
Promise.all(cacheNames.filter((cacheName) => cacheName !== CACHE_NAME).map((cacheName) => caches.delete(cacheName)))
|
|
)
|
|
);
|
|
});
|
|
|
|
self.addEventListener("fetch", (event) => {
|
|
const { request } = event;
|
|
const url = new URL(request.url);
|
|
|
|
if (request.method !== "GET" || url.pathname.startsWith("/api")) {
|
|
return;
|
|
}
|
|
|
|
event.respondWith(
|
|
fetch(request)
|
|
.then((response) => {
|
|
const responseClone = response.clone();
|
|
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
cache.put(request, responseClone);
|
|
});
|
|
|
|
return response;
|
|
})
|
|
.catch(async () => {
|
|
const cached = await caches.match(request);
|
|
return cached ?? caches.match("/");
|
|
})
|
|
);
|
|
});
|