-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.ts
63 lines (54 loc) · 1.47 KB
/
cache.ts
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
55
56
57
58
59
60
61
62
63
import sha from 'sha-1'
import { readJsonFile, writeJsonFile } from './fs-read-write'
type CacheEntry<V> =
| {
status: 'done'
expiresAt: number
value: V
}
| {
status: 'pending'
expiresAt: number
}
export function getCached<V>(
key: string,
fn: () => Promise<V>,
cacheDurationMs: number
) {
//
const getEntry = async (): Promise<CacheEntry<V> | undefined> =>
readJsonFile(`./.cache-${sha(key)}.json`)
const writePendingEntry = () =>
writeJsonFile(`./.cache-${sha(key)}.json`, {
status: 'pending',
expiresAt: new Date().getTime() + 10000,
})
const writeEntry = async (value: V) =>
writeJsonFile(`./.cache-${sha(key)}.json`, {
status: 'done',
expiresAt: new Date().getTime() + cacheDurationMs,
value,
})
const wait = (t: number) => new Promise((resolve) => setTimeout(resolve, t))
const revalidate = async (): Promise<V> => {
await writePendingEntry()
const value = await fn()
await writeEntry(value)
return value
}
const hasExpired = (entry: CacheEntry<V>) =>
new Date().getTime() > entry.expiresAt
const getValue = async (): Promise<V> => {
const entry = await getEntry()
if (entry) {
if (entry.status === 'done' && !hasExpired(entry)) {
return entry.value
} else if (entry.status === 'pending' && !hasExpired(entry)) {
await wait(500)
return getValue()
}
}
return revalidate()
}
return getValue()
}