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