fix(pwa): 🐛 replace Promise.any by promise chain to avoid insufficient resources at sw runtime

This commit is contained in:
Julien Oculi 2024-07-19 14:45:52 +02:00
parent 3c35dcbf8e
commit 0b3c374c79

View file

@ -5,66 +5,46 @@ export class FetchStrategy {
)
}
static fastestAndCacheRefresh(
static async cacheFirst(
cache: Cache,
{ request, preloadResponse }: Pick<
FetchEvent,
'request' | 'preloadResponse'
>,
ac = new AbortController(),
cacheQueryOptions?: CacheQueryOptions | undefined,
) {
// Get cache or throw
const cachedOrError = cache.match(request)
.then((response) => {
if (response) {
// Abort network request
ac.abort()
return response
}
throw new Error(`no cache available for "${request.url}"`)
})
// Get cache
const cached = await cache.match(request, cacheQueryOptions)
if (cached) {
return cached
}
// Fetch and cache
const fetchedAndCached = this.networkOnly({ request, preloadResponse }, ac)
.then((response) => {
// Abort cache request
ac.abort()
// Update cache
cache.put(request, response.clone())
return response
})
const fetched = await this.networkOnly({ request, preloadResponse })
cache.put(request, fetched.clone())
return fetched
}
// Get fastest
return Promise.any([cachedOrError, fetchedAndCached])
}
static networkOnly(
static async networkOnly(
{ request, preloadResponse }: Pick<
FetchEvent,
'request' | 'preloadResponse'
>,
ac = new AbortController(),
): Promise<Response> {
// Browser preload
const preload = getPreload(preloadResponse, ac)
.then((response) => {
if (response === undefined) {
throw new Error(`no preload response for ${request.url}`)
}
// Cancel fetch event
ac.abort()
return response
})
const preloaded = await getPreload(preloadResponse)
// Client fetch
const fetched = fetch(request, { signal: ac.signal })
.then((response) => {
// Cancel preload event
ac.abort()
return response
})
if (preloaded) {
return preloaded
}
return Promise.any([preload, fetched])
// Fetch
return fetch(request)
}
}