-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcache.ts
More file actions
66 lines (50 loc) · 1.55 KB
/
Copy pathcache.ts
File metadata and controls
66 lines (50 loc) · 1.55 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
55
56
57
58
59
60
61
62
63
64
65
66
import { defaultConfigReader as config } from '../config-reader';
const DEFAULT_CACHE_TIME_MILLISECONDS = 60_000 * 10; // 10 minutes
type Result<T> = {
value: T;
cacheTime?: number;
};
const newCache = <KeyType, ValueType>(
getCurrentTime: () => Date,
fetch: (k: KeyType) => Promise<Result<ValueType>>,
) => {
const cacheTimeMilliSec =
config.tryGetInt('DEFAULT_CACHE_TIME_MILLISECONDS') ??
DEFAULT_CACHE_TIME_MILLISECONDS;
type Holder = {
value: ValueType;
timestamp: Date | undefined;
};
type State = Record<string, Holder>;
let state: State = {};
let stateCacheTime = 0;
async function getCachedAsync(key: KeyType): Promise<ValueType> {
const flatKey: string = typeof key === 'string' ? key : JSON.stringify(key);
const currentTime = getCurrentTime();
const holder: Holder = state[flatKey];
if (
holder?.timestamp &&
// eslint-disable-next-line sonarjs/different-types-comparison
stateCacheTime !== undefined &&
currentTime.getTime() - holder.timestamp.getTime() < stateCacheTime
) {
return holder.value;
}
// value not cached or expired, so fetch a new value from upstream
const result: Result<ValueType> = await fetch(key);
const cacheTime = result.cacheTime ?? cacheTimeMilliSec;
if (cacheTime) {
stateCacheTime = cacheTime;
}
state[flatKey] = {
value: result.value,
timestamp: currentTime,
};
return result.value;
}
function clear() {
state = {};
}
return { getCachedAsync, clear };
};
export { newCache };