feat(pwa): add new sw "fastest and cache refresh" fetch strategy

This commit is contained in:
Julien Oculi 2024-07-18 15:42:03 +02:00
parent 9bf6d9596c
commit 77f9ae3518

View file

@ -27,6 +27,35 @@ export class Strategy {
return this.#cache.match(request)
}
fastestAndCacheRefresh(
{ request, preloadResponse }: Pick<FetchEvent, 'request' | 'preloadResponse'>,
ac: AbortController = new AbortController()
) {
// Get cache or throw
const cachedOrError = this.#cache.match(request)
.then((response) => {
if (response) {
// Abort network request
ac.abort()
return response
}
throw new Error(`no cache available for "${request.url}"`)
})
// Fetch and cache
const fetchedAndCached = this.networkOnly({ request, preloadResponse}, ac)
.then((response) => {
// Abort cache request
ac.abort()
// Update cache
this.#cache.put(request, response.clone())
return response
})
// Get fastest
return Promise.race([cachedOrError, fetchedAndCached])
}
async networkFirst(
{ request, preloadResponse }: FetchEvent,
{ fallbackUrl, timeout }: { fallbackUrl?: string; timeout?: number },