| |
| |
| |
| |
| |
| |
| |
|
|
| const CACHE_NAME = 'medos-v1'; |
| const APP_SHELL_CACHE = 'medos-shell-v1'; |
| const FAQ_CACHE = 'medos-faq-v1'; |
|
|
| const APP_SHELL_URLS = [ |
| '/', |
| '/manifest.json', |
| ]; |
|
|
| |
| self.addEventListener('install', (event) => { |
| event.waitUntil( |
| caches.open(APP_SHELL_CACHE).then((cache) => { |
| return cache.addAll(APP_SHELL_URLS); |
| }) |
| ); |
| self.skipWaiting(); |
| }); |
|
|
| |
| self.addEventListener('activate', (event) => { |
| event.waitUntil( |
| caches.keys().then((cacheNames) => { |
| return Promise.all( |
| cacheNames |
| .filter( |
| (name) => |
| name !== APP_SHELL_CACHE && |
| name !== FAQ_CACHE && |
| name !== CACHE_NAME |
| ) |
| .map((name) => caches.delete(name)) |
| ); |
| }) |
| ); |
| self.clients.claim(); |
| }); |
|
|
| |
| self.addEventListener('fetch', (event) => { |
| const { request } = event; |
| const url = new URL(request.url); |
|
|
| |
| if (url.pathname.startsWith('/api/')) { |
| event.respondWith( |
| fetch(request) |
| .then((response) => { |
| |
| if (request.method === 'GET' && response.ok) { |
| const cloned = response.clone(); |
| caches.open(CACHE_NAME).then((cache) => cache.put(request, cloned)); |
| } |
| return response; |
| }) |
| .catch(() => { |
| |
| return caches.match(request).then((cached) => { |
| if (cached) return cached; |
| return new Response( |
| JSON.stringify({ |
| error: 'offline', |
| message: 'You are currently offline. Please try again when connected.', |
| }), |
| { |
| status: 503, |
| headers: { 'Content-Type': 'application/json' }, |
| } |
| ); |
| }); |
| }) |
| ); |
| return; |
| } |
|
|
| |
| event.respondWith( |
| caches.match(request).then((cached) => { |
| if (cached) return cached; |
| return fetch(request).then((response) => { |
| if (response.ok && request.method === 'GET') { |
| const cloned = response.clone(); |
| caches.open(CACHE_NAME).then((cache) => cache.put(request, cloned)); |
| } |
| return response; |
| }); |
| }) |
| ); |
| }); |
|
|