feat(pwa): add new "network first" fetch strategy

This commit is contained in:
Julien Oculi 2024-07-19 14:46:27 +02:00
parent 0b3c374c79
commit 76c6b597a8

View file

@ -26,8 +26,32 @@ export class FetchStrategy {
return fetched return fetched
} }
// Get fastest static async networkFirst(
return Promise.any([cachedOrError, fetchedAndCached]) cache: Cache,
{ request, preloadResponse }: Pick<
FetchEvent,
'request' | 'preloadResponse'
>,
cacheQueryOptions?: CacheQueryOptions | undefined,
): Promise<Response> {
try {
// Fetch and cache
const fetched = await this.networkOnly({ request, preloadResponse })
cache.put(request, fetched.clone())
return fetched
} catch (cause) {
// Get cache
const cached = await cache.match(request, cacheQueryOptions)
if (cached) {
return cached
}
throw new Error(
`no cache available for the requested url "${request.url}"`,
{ cause },
)
}
} }
static async networkOnly( static async networkOnly(