diff --git a/client/public/sw.js b/client/public/sw.js index ebc252d..2ab04af 100644 --- a/client/public/sw.js +++ b/client/public/sw.js @@ -1,4 +1,4 @@ -const CACHE_VERSION = 'editty-cache-v2' +const CACHE_VERSION = 'editty-cache-v3' const ICON_PATH = '/assets/images' const ICON_CACHE = [ @@ -22,35 +22,58 @@ const ICON_CACHE = [ ].map((icon) => `${ICON_PATH}/${icon}.svg`) const PAGE_CACHE = ['./index.html', './manifest.json'] +self.addEventListener('activate', (ev) => { + ev.waitUntil(deleteOldCache()) +}) + +async function deleteOldCache() { + const cacheKeys = await caches.keys() + const cacheToDelete = cacheKeys.filter((key) => key !== CACHE_VERSION) + const deleteCacheJobs = cacheToDelete.map(deleteCache) + await Promise.all(deleteCacheJobs) +} + +async function deleteCache(key) { + await caches.delete(key) +} + self.addEventListener('install', (ev) => { - ev.waitUntil( - (async () => { - const cache = await caches.open(CACHE_VERSION) - return cache.addAll([...ICON_CACHE, ...PAGE_CACHE]) - })() - ) + ev.waitUntil(cacheResource()) }) -self.addEventListener('fetch', (ev) => { +async function cacheResource() { + const cache = await caches.open(CACHE_VERSION) + return cache.addAll([...ICON_CACHE, ...PAGE_CACHE]) +} + +self.addEventListener('fetch', async (ev) => { if (ev.request.method !== 'GET') { return } - ev.respondWith( - (async () => { - const cache = await caches.open(CACHE_VERSION) + ev.respondWith(cacheFirst(ev.request)) +}) - let resource = null +async function cacheFirst(request) { + const cachedResponse = await caches.match(request) - try { - const response = await fetch(ev.request) - cache.put(ev.request, response.clone()) - resource = response - } catch { - resource = await cache.match(ev.request) - } + if (cachedResponse) { + return cachedResponse + } - return resource - })() - ) -}) + try { + const response = await fetch(request) + putCache(request, response) + return response + } catch { + return new Response('Network error!', { + status: 408, + headers: { 'Content-Type': 'text/plain' }, + }) + } +} + +async function putCache(request, response) { + const cache = await caches.open(CACHE_VERSION) + cache.put(request, response.clone()) +}