57 lines
1.8 KiB
JavaScript
57 lines
1.8 KiB
JavaScript
// Service worker for the /repairs-app PWA.
|
|
//
|
|
// A shell cache, NOT an offline app. The repairs person always has
|
|
// signal, so live data must never be served stale: the fetch handler
|
|
// ignores /api/ entirely and only the shell is cached.
|
|
const CACHE_NAME = "wfdash-repairs-app-v1";
|
|
|
|
const PRECACHE_ASSETS = [
|
|
"/repairs-app",
|
|
"/manifest-repairs-app.json",
|
|
"/offline",
|
|
"/android-chrome-192x192.png",
|
|
"/android-chrome-512x512.png",
|
|
"/apple-touch-icon.png",
|
|
];
|
|
|
|
self.addEventListener("install", (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => cache.addAll(PRECACHE_ASSETS))
|
|
);
|
|
self.skipWaiting();
|
|
});
|
|
|
|
self.addEventListener("activate", (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((keys) =>
|
|
Promise.all(
|
|
// Only THIS app's own caches are evicted. All six workers on
|
|
// this origin share the scope "/", so the last-visited app's
|
|
// worker takes over the origin — and deleting the other apps'
|
|
// caches would wipe the app the operator is actually using.
|
|
// The current cache stays: it was just precached on install.
|
|
keys
|
|
.filter((k) => k.startsWith("wfdash-repairs-app-") && k !== CACHE_NAME)
|
|
.map((k) => caches.delete(k))
|
|
)
|
|
)
|
|
);
|
|
self.clients.claim();
|
|
});
|
|
|
|
self.addEventListener("fetch", (event) => {
|
|
const { request } = event;
|
|
if (request.method !== "GET") return;
|
|
|
|
const url = new URL(request.url);
|
|
if (url.origin !== self.location.origin) return;
|
|
// Never serve API data from the cache — a stale repair list is worse
|
|
// than no repair list.
|
|
if (url.pathname.startsWith("/api/")) return;
|
|
|
|
event.respondWith(
|
|
fetch(request).catch(() =>
|
|
caches.match(request).then((cached) => cached || caches.match("/offline"))
|
|
)
|
|
);
|
|
});
|