-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
31 lines (28 loc) · 840 Bytes
/
utils.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
export interface CacheOptions {
revalidate?: number;
}
interface CacheEntry<T> {
value: T,
updatedAt: Date,
}
export function cache<T>(func: (arg: string) => T, options: CacheOptions = {}) {
const revalidate = options?.revalidate ?? 300;
const cache: Record<string, CacheEntry<T>|undefined> = {};
return function cached(arg: string) {
const cachedEntry = cache[arg];
if (cachedEntry && (+new Date() - +cachedEntry.updatedAt) <= revalidate * 1000) {
return cachedEntry.value;
}
const result = func(arg);
cache[arg] = {
updatedAt: new Date(),
value: result,
};
if (result instanceof Promise) {
result.catch(() => {
cache[arg] = undefined;
});
}
return result;
}
}