Files
wtr/public/sw.js
zv ee55521803
All checks were successful
CI / Lint, typecheck and build (push) Successful in 9m56s
chore: add prettier formatting
2026-06-14 20:26:56 +02:00

95 lines
2.6 KiB
JavaScript

const CACHE_NAME = "wtr-shell-v5";
const SHELL = [
"/",
"/settings",
"/offline",
"/manifest.json",
"/icons/icon.svg",
"/icons/maskable.svg",
"/icons/icon-192.png",
"/icons/icon-512.png",
"/icons/maskable-512.png",
];
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(SHELL)));
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key)))),
);
self.clients.claim();
});
self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") return;
const url = new URL(event.request.url);
if (
url.pathname.startsWith("/api/imgw/") ||
url.pathname === "/api/imgw-current" ||
url.pathname === "/api/current-weather" ||
url.pathname === "/api/forecast"
) {
event.respondWith(
fetch(event.request)
.then((response) => {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy));
return response;
})
.catch(() => caches.match(event.request)),
);
return;
}
if (event.request.mode === "navigate") {
event.respondWith(
fetch(event.request).catch(() =>
caches.match(event.request).then((response) => response || caches.match("/offline")),
),
);
}
});
self.addEventListener("push", (event) => {
const fallbackPayload = {
title: "IMGW",
body: "Nowe ostrzeżenie meteorologiczne.",
url: "/warnings",
};
let payload = fallbackPayload;
if (event.data) {
const text = event.data.text();
try {
payload = { ...fallbackPayload, ...JSON.parse(text) };
} catch {
payload = { ...fallbackPayload, body: text };
}
}
event.waitUntil(
self.registration.showNotification(payload.title, {
body: payload.body,
icon: "/icons/icon-192.png",
badge: "/icons/icon-192.png",
data: { url: payload.url || "/warnings" },
}),
);
});
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const targetUrl = new URL(event.notification.data?.url || "/warnings", self.location.origin).href;
event.waitUntil(
self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((clients) => {
const existingClient = clients.find((client) => client.url === targetUrl);
if (existingClient) return existingClient.focus();
return self.clients.openWindow(targetUrl);
}),
);
});