-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathc.js
58 lines (55 loc) · 1.32 KB
/
c.js
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
export class DataWithExpiry {
constructor(expiryDuration, _data) {
this._data = _data;
this.expiryTime = expiryDuration + Date.now();
}
get expired() {
const hasExpired = this.expiryTime <= Date.now();
if (hasExpired) {
this._data = undefined;
}
return hasExpired;
}
get data() {
if (this.expired) {
this._data = undefined;
}
return this._data;
}
}
const globalCacheStore = new Map();
export function getGlobalCacheStore() {
return globalCacheStore;
}
export class InMemoryCache {
constructor(expiryDurationMs, cacheKey = "") {
this.expiryDurationMs = expiryDurationMs;
this.cacheKey = cacheKey;
}
get hasData() {
const store = globalCacheStore.get(this.cacheKey);
return store && !store.expired ? true : false;
}
/**
* Returns undefined if there is no data.
* Uses `hasData` to determine whether any cached data exists.
*
* @readonly
* @type {(T | undefined)}
* @memberof InMemoryCache
*/
get data() {
if (!this.hasData) {
return;
}
const store = globalCacheStore.get(this.cacheKey);
return store?.data;
}
set data(value) {
const store = new DataWithExpiry(this.expiryDurationMs, value);
globalCacheStore.set(this.cacheKey, store);
}
clear() {
globalCacheStore.delete(this.cacheKey);
}
}