-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.js
65 lines (53 loc) · 1.47 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
const { Undefined } = require('./validations');
class Cache {
static cache = {};
static capabilities = 'capabilities';
static sessionCapabilities = 'session_capabilites';
static commandExecutorUrl = 'command_executor_url';
static lastTime = Date.now();
static timeout = 5 * 60 * 1000;
static async withCache(store, key, func, cacheExceptions = false) {
this.maintain();
if (Undefined(this.cache[store])) this.cache[store] = {};
store = this.cache[store];
if (store[key]) {
if (store[key].success) {
return store[key].val;
} else {
throw store[key].val;
}
}
const obj = { success: false, val: null, time: Date.now() };
try {
obj.val = await func();
obj.success = true;
} catch (e) {
obj.val = e;
}
// We seem to have correct coverage for both flows but nyc is marking it as missing
// branch coverage anyway
/* istanbul ignore next */
if (obj.success || cacheExceptions) {
store[key] = obj;
}
if (!obj.success) throw obj.val;
return obj.val;
}
static maintain() {
if (this.lastTime + this.timeout > Date.now()) return;
for (const [, store] of Object.entries(this.cache)) {
for (const [key, item] of Object.entries(store)) {
if (item.time + this.timeout < Date.now()) {
delete store[key];
}
}
}
this.lastTime = Date.now();
}
static reset() {
this.cache = {};
}
}
module.exports = {
Cache
};