-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.js
93 lines (72 loc) · 1.8 KB
/
cache.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Cache {
cache = new Map();
clearTimeouts = {};
revalidateTimeouts = {};
get(key) {
return this.cache.get(key);
}
set(key, value, options = {}) {
const { clear = true, clearTimeout = 60 } = options;
this.cache.set(key, value);
if (clear) {
this.deleteClearTimeout(key);
const timeout = setTimeout(() => {
this.delete(key);
delete this.clearTimeouts[key];
}, clearTimeout * 1000);
this.clearTimeouts[key] = timeout;
}
}
delete(key) {
this.deleteClearTimeout(key);
this.deleteRevalidateTimeout(key);
return this.cache.delete(key);
}
has(key) {
return this.cache.has(key);
}
clear() {
this.cache.clear();
this.deleteAllClearTimeouts();
this.deleteAllRevalidateTimeouts();
}
revalidate(key, callback, timeout) {
const timeoutKey = setTimeout(async () => {
try {
delete this.revalidateTimeouts[key];
const data = await callback();
if (data) {
this.set(key, data);
}
} catch (e) {
console.error('revalidate', key, e);
}
}, (timeout || 60) * 1000);
this.revalidateTimeouts[key] = timeoutKey;
}
deleteClearTimeout(key) {
const timeout = this.clearTimeouts[key];
if (timeout) {
clearTimeout(timeout);
delete this.clearTimeouts[key];
}
}
deleteAllClearTimeouts() {
for (const key in this.clearTimeouts) {
this.deleteClearTimeout(key);
}
}
deleteRevalidateTimeout(key) {
const timeout = this.revalidateTimeouts[key];
if (timeout) {
clearTimeout(timeout);
delete this.revalidateTimeouts[key];
}
}
deleteAllRevalidateTimeouts() {
for (const key in this.revalidateTimeouts) {
this.deleteRevalidateTimeout(key);
}
}
}
export default Cache;