Skip to content

Commit 12dd0e6

Browse files
committed
fix: add stale cache handling to fetchCached function
1 parent 3259b34 commit 12dd0e6

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

src/utils/cache.server.ts

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import LRUCache from 'lru-cache'
22

33
declare global {
44
var docCache: LRUCache<string, unknown>
5+
var docStaleCache: LRUCache<string, unknown>
56
}
67

78
const 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+
1522
export 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
}

src/utils/documents.server.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff 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)

0 commit comments

Comments
 (0)