feat: improve caching

- if addAll failed, show helpful log
- only cache if response.ok
- use more async by removing unnecessary awaits
This commit is contained in:
Ayo Ayco 2024-08-23 12:26:53 +02:00
parent 8a4ef035fc
commit e84ac825f0
2 changed files with 21 additions and 10 deletions

View file

@ -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_PROJECT_REPO = 'https://github.com/ayoayco/Cozy';
export const SITE_DESCRIPTION = 'The Web is Yours.'; export const SITE_DESCRIPTION = 'The Web is Yours.';
export const VERSION = 'Singing-Sirens'; export const VERSION = 'Tired-Tourists';

View file

@ -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` * Note: @ayco/astro-sw integration injects variables `__prefix`, `__version`, & `__assets`
* -- find usage in `astro.config.mjs` integrations * -- find usage in `astro.config.mjs` integrations
@ -21,20 +21,31 @@ const cleanOldCaches = async () => {
const addResourcesToCache = async (resources) => { const addResourcesToCache = async (resources) => {
const cache = await caches.open(cacheName); const cache = await caches.open(cacheName);
logInfo('adding resources to cache...', { force: !!forceLogging, context: 'cozy-sw', data: resources }) logInfo('adding resources to cache...', { force: !!forceLogging, context: 'cozy-sw', data: resources })
try {
await cache.addAll(resources); 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 putInCache = async (request, response) => {
const cache = await caches.open(cacheName); 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 (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)) { if (keys.includes(request)) {
cache.delete(request); cache.delete(request);
} }
});
await cache.put(request, response); cache.put(request, response);
}
}; };