81 lines
2.4 KiB
JavaScript
81 lines
2.4 KiB
JavaScript
|
|
// Service worker for the /manager orders PWA. Precaches the mobile
|
||
|
|
// shell, network-first for navigations, never caches the orders API
|
||
|
|
// responses (those are live tracking data — a stale count would
|
||
|
|
// actively mislead the manager).
|
||
|
|
const CACHE_NAME = "wfdash-manager-v1";
|
||
|
|
const OFFLINE_URL = "/offline";
|
||
|
|
|
||
|
|
const PRECACHE_ASSETS = [
|
||
|
|
"/manager",
|
||
|
|
"/manifest-manager.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);
|
||
|
|
|
||
|
|
// Never cache API traffic — the order pipeline is live tracking data
|
||
|
|
// and serving a stale /api/v1/manager-orders would show the manager
|
||
|
|
// orders that have already moved on.
|
||
|
|
if (url.pathname.startsWith("/api/")) return;
|
||
|
|
|
||
|
|
// Navigation requests: network-first, fall back to the cached
|
||
|
|
// /manager shell, then the generic /offline page.
|
||
|
|
if (request.mode === "navigate") {
|
||
|
|
event.respondWith(
|
||
|
|
fetch(request)
|
||
|
|
.then((response) => {
|
||
|
|
const clone = response.clone();
|
||
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, clone));
|
||
|
|
return response;
|
||
|
|
})
|
||
|
|
.catch(async () => {
|
||
|
|
const cached = await caches.match(request);
|
||
|
|
if (cached) return cached;
|
||
|
|
const managerShell = await caches.match("/manager");
|
||
|
|
if (managerShell) return managerShell;
|
||
|
|
return caches.match(OFFLINE_URL);
|
||
|
|
})
|
||
|
|
);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Static assets: stale-while-revalidate.
|
||
|
|
event.respondWith(
|
||
|
|
caches.match(request).then((cached) => {
|
||
|
|
const networkFetch = fetch(request)
|
||
|
|
.then((response) => {
|
||
|
|
const clone = response.clone();
|
||
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, clone));
|
||
|
|
return response;
|
||
|
|
})
|
||
|
|
.catch(() => cached);
|
||
|
|
return cached || networkFetch;
|
||
|
|
})
|
||
|
|
);
|
||
|
|
});
|