meteo-exam/web/public/sw.js

40 lines
1.2 KiB
JavaScript
Raw Normal View History

/**
* Service worker Météo Exam.
* - Cache les assets statiques (app shell) pour un démarrage hors ligne.
* - Les appels API passent en network-first : les données restent fraîches.
*/
const CACHE_NAME = 'meteo-exam-v2'
const STATIC_ASSETS = ['/', '/index.html', '/manifest.webmanifest']
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(STATIC_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
const url = new URL(request.url)
// API et flux SSE : toujours réseau, pas de cache.
if (url.pathname.startsWith('/api/')) return
// Assets statiques : cache d'abord, réseau en secours.
if (request.method === 'GET' && (url.origin === self.location.origin || url.hostname === 'localhost')) {
event.respondWith(
caches.match(request).then((cached) => cached ?? fetch(request).catch(() => caches.match('/index.html'))),
)
}
})