From e84ac825f04ce173e0e6f8d8b4329e5406aebdba Mon Sep 17 00:00:00 2001 From: ayoayco Date: Fri, 23 Aug 2024 12:26:53 +0200 Subject: [PATCH] feat: improve caching - if addAll failed, show helpful log - only cache if response.ok - use more async by removing unnecessary awaits --- src/consts.ts | 2 +- src/sw.mjs | 29 ++++++++++++++++++++--------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/src/consts.ts b/src/consts.ts index ee6fb68..04bc485 100644 --- a/src/consts.ts +++ b/src/consts.ts @@ -6,4 +6,4 @@ export const SITE_AUTHOR_MASTODON = 'https://social.ayco.io/@ayo'; export const SITE_PROJECT_REPO = 'https://github.com/ayoayco/Cozy'; export const SITE_DESCRIPTION = 'The Web is Yours.'; -export const VERSION = 'Singing-Sirens'; \ No newline at end of file +export const VERSION = 'Tired-Tourists'; \ No newline at end of file diff --git a/src/sw.mjs b/src/sw.mjs index d387643..08427bd 100644 --- a/src/sw.mjs +++ b/src/sw.mjs @@ -1,4 +1,4 @@ -import { logInfo } from './utils/logger' +import { logError, logInfo } from './utils/logger' /** * Note: @ayco/astro-sw integration injects variables `__prefix`, `__version`, & `__assets` * -- find usage in `astro.config.mjs` integrations @@ -21,20 +21,31 @@ const cleanOldCaches = async () => { const addResourcesToCache = async (resources) => { const cache = await caches.open(cacheName); logInfo('adding resources to cache...', { force: !!forceLogging, context: 'cozy-sw', data: resources }) - await cache.addAll(resources); + try { + await cache.addAll(resources); + } catch(error) { + logError('failed to add resources to cache; make sure requests exists and that there are no duplicates', {force: !!forceLogging, context: 'cozy-sw', data: { + resources, + error + }}) + } }; const putInCache = async (request, response) => { const cache = await caches.open(cacheName); - logInfo('adding one response to cache...', { force: forceLogging, context: 'cozy-sw', data: request.url }) - // if exists, replace - const keys = await cache.keys(); - if (keys.includes(request)) { - cache.delete(request); + if (response.ok) { + logInfo('adding one response to cache...', { force: forceLogging, context: 'cozy-sw', data: request.url }) + + // if exists, replace + cache.keys().then( keys => { + if (keys.includes(request)) { + cache.delete(request); + } + }); + + cache.put(request, response); } - - await cache.put(request, response); };