File tree Expand file tree Collapse file tree 2 files changed +29
-5
lines changed
Expand file tree Collapse file tree 2 files changed +29
-5
lines changed Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ import LRUCache from 'lru-cache'
22
33declare global {
44 var docCache : LRUCache < string , unknown >
5+ var docStaleCache : LRUCache < string , unknown >
56}
67
78const docCache =
@@ -12,20 +13,42 @@ const docCache =
1213 ttl : process . env . NODE_ENV === 'production' ? 1 : 1000000 ,
1314 } ) )
1415
16+ const docStaleCache =
17+ globalThis . docStaleCache ||
18+ ( globalThis . docStaleCache = new LRUCache < string , unknown > ( {
19+ max : 300 ,
20+ } ) )
21+
1522export async function fetchCached < T > ( opts : {
1623 fn : ( ) => Promise < T >
1724 key : string
1825 ttl : number
26+ staleOnError ?: boolean
1927} ) : Promise < T > {
2028 if ( docCache . has ( opts . key ) ) {
2129 return docCache . get ( opts . key ) as T
2230 }
2331
24- const result = await opts . fn ( )
32+ try {
33+ const result = await opts . fn ( )
2534
26- docCache . set ( opts . key , result , {
27- ttl : opts . ttl ,
28- } )
35+ docCache . set ( opts . key , result , {
36+ ttl : opts . ttl ,
37+ } )
2938
30- return result
39+ if ( opts . staleOnError ) {
40+ docStaleCache . set ( opts . key , result )
41+ }
42+
43+ return result
44+ } catch ( error ) {
45+ if ( opts . staleOnError && docStaleCache . has ( opts . key ) ) {
46+ console . warn (
47+ `[fetchCached] Serving stale value for key '${ opts . key } ' after fetch error` ,
48+ )
49+ return docStaleCache . get ( opts . key ) as T
50+ }
51+
52+ throw error
53+ }
3154}
Original file line number Diff line number Diff line change @@ -423,6 +423,7 @@ export function fetchApiContents(
423423 return fetchCached ( {
424424 key : `${ repoPair } :${ branch } :${ startingPath } ` ,
425425 ttl : isDev ? 1 : 10 * 60 * 1000 , // 10 minute
426+ staleOnError : true ,
426427 fn : ( ) => {
427428 return isDev
428429 ? fetchApiContentsFs ( repoPair , startingPath )
You can’t perform that action at this time.
0 commit comments