50 lines
1.4 KiB
JavaScript
50 lines
1.4 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(
|
|
keys.filter((k) => 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"))
|
|
)
|
|
);
|
|
});
|