feat(pwa): handle new fetch strategies

This commit is contained in:
Julien Oculi 2024-07-19 14:58:55 +02:00
parent 574c60c130
commit 79b91aad92

View file

@ -136,31 +136,24 @@ async function fetchHandler(event: FetchEvent) {
updatePreCache()
// TODO handle search params
const ac = new AbortController()
const preCachedNoSearch = preCache
.match(event.request, { ignoreSearch: true })
.then((response) => {
if (response) {
ac.abort()
return response
}
throw new Error(`no cache available for pre-cached-url "${url}"`)
})
return Promise.any([
FetchStrategy.fastestAndCacheRefresh(preCache, event, ac),
preCachedNoSearch,
])
return FetchStrategy.cacheFirst(preCache, event, { ignoreSearch: true })
}
// Fastest and cache refresh
if (url.origin === location.origin && method === 'GET') {
const cache = await getDynCache()
FetchStrategy.fastestAndCacheRefresh(cache, event)
// Allow offline API results
if (url.pathname.startsWith('/api/')) {
const cache = await getCache('$sw.api-cache.version')
return FetchStrategy.networkFirst(cache, event)
}
async function getCache(name: string, lifeTime = 1 * 24 * 3_600 * 1000): Promise<Cache> {
// Cache first else fetch and cache refresh
const cache = await getCache('$sw.dyn-cache.version')
return FetchStrategy.cacheFirst(cache, event)
}
async function getCache(
name: string,
lifeTime = 1 * 24 * 3_600 * 1000,
): Promise<Cache> {
const now = Date.now()
const version = await swStorage.getItem<number>(name)