forked from TanStack/tanstack.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.server.ts
More file actions
54 lines (45 loc) · 1.14 KB
/
cache.server.ts
File metadata and controls
54 lines (45 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import LRUCache from 'lru-cache'
declare global {
var docCache: LRUCache<string, unknown>
var docStaleCache: LRUCache<string, unknown>
}
const docCache =
globalThis.docCache ||
(globalThis.docCache = new LRUCache<string, unknown>({
max: 300,
// ttl: 1,
ttl: process.env.NODE_ENV === 'production' ? 1 : 1000000,
}))
const docStaleCache =
globalThis.docStaleCache ||
(globalThis.docStaleCache = new LRUCache<string, unknown>({
max: 300,
}))
export async function fetchCached<T>(opts: {
fn: () => Promise<T>
key: string
ttl: number
staleOnError?: boolean
}): Promise<T> {
if (docCache.has(opts.key)) {
return docCache.get(opts.key) as T
}
try {
const result = await opts.fn()
docCache.set(opts.key, result, {
ttl: opts.ttl,
})
if (opts.staleOnError) {
docStaleCache.set(opts.key, result)
}
return result
} catch (error) {
if (opts.staleOnError && docStaleCache.has(opts.key)) {
console.warn(
`[fetchCached] Serving stale value for key '${opts.key}' after fetch error`,
)
return docStaleCache.get(opts.key) as T
}
throw error
}
}