-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcache.js
44 lines (36 loc) · 890 Bytes
/
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
const NodeCache = require("node-cache");
class CacheService {
constructor(ttlSeconds) {
this.cache = new NodeCache({ stdTTL: ttlSeconds, checkperiod: ttlSeconds * 0.2, useClones: false });
}
get(key, storeFunction, ttl) {
const value = this.cache.get(key);
if (value) {
console.log(`Get ${key} from cache`);
return Promise.resolve(value);
}
return storeFunction().then((result) => {
console.log(`Get ${key} from function`);
this.cache.set(key, result, ttl);
return result;
});
}
del(keys) {
this.cache.del(keys);
}
delStartWith(startStr = "") {
if (!startStr) {
return;
}
const keys = this.cache.keys();
for (const key of keys) {
if (key.indexOf(startStr) === 0) {
this.del(key);
}
}
}
flush() {
this.cache.flushAll();
}
}
module.exports = CacheService;