Skip to content

Commit

Permalink
feat(fetch): stale_while_revalidate cache strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
AliMD committed Oct 21, 2022
1 parent f2bd8f2 commit f758f49
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions packages/core/fetch/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ declare global {
}
}

export type CacheStrategy = 'network_only' | 'network_first' | 'cache_only' | 'cache_first' | 'stale_while_revalidate'
export type CacheStrategy = 'network_only' | 'network_first' | 'cache_only' | 'cache_first' | 'stale_while_revalidate';

// @TODO: docs for all options
export interface FetchOptions extends RequestInit {
Expand All @@ -41,9 +41,9 @@ export interface FetchOptions extends RequestInit {
*
* @default 'network_only'
*/
cacheStrategy: CacheStrategy;
cacheStrategy: CacheStrategy;

/**
/**
* Cache storage name.
*
* @default 'alwatr_fetch_cache'
Expand Down Expand Up @@ -117,7 +117,16 @@ export async function fetch(_options: Partial<FetchOptions> & {url: string}): Pr
}
}

// case 'stale_while_revalidate': {}
case 'stale_while_revalidate': {
const cachedResponse = await cacheStorage.match(request);
const fetchedResponsePromise = _fetch(options).then((networkResponse) => {
if (networkResponse.ok) {
cacheStorage.put(request, networkResponse.clone());
}
return networkResponse;
});
return cachedResponse || fetchedResponsePromise;
}

default: {
return _fetch(options);
Expand Down

0 comments on commit f758f49

Please sign in to comment.