-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
99 lines (93 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
94
95
96
97
98
99
const Redis = require('ioredis');
const hash = require('object-hash');
const REDIS_URL = process.env.REDIS_URL || 'redis://redis:6379';
const cache = new Redis(`${REDIS_URL}/2`);
const defaultTTL = 60 * 60; // 1 hour
const save = async ({
pluginName,
key: keyParam,
value,
skipTTL,
ttl = defaultTTL,
}) => {
const key = `${pluginName}:${(() => {
if (typeof keyParam !== 'string') {
return hash(keyParam);
}
return keyParam;
})()}`;
await cache.set(key, JSON.stringify(value));
if (!skipTTL) {
await cache.expire(key, ttl);
}
};
const get = async ({
pluginName,
key: keyParam,
}) => {
const key = `${pluginName}:${(() => {
if (typeof keyParam !== 'string') {
return hash(keyParam);
}
return keyParam;
})()}`;
const storeVal = await cache.get(key);
if (!storeVal) return storeVal;
return JSON.parse(storeVal);
};
const getOrExec = async ({
pluginName,
key: keyParam,
ttl,
fn,
fnParams,
forceRefresh,
}) => {
const key = (() => {
if (!keyParam) {
return hash({ fn, fnParams });
}
if (typeof keyParam !== 'string') {
return hash(keyParam);
}
return keyParam;
})();
let value;
if (!forceRefresh) {
value = await get({ pluginName, key });
if (value !== null) return value;
}
value = await fn(...fnParams);
await save({
pluginName,
key,
value,
ttl,
});
return value;
};
const drop = async ({
pluginName,
key: keyParam,
fn,
fnParams,
}) => {
let key = `${pluginName}:${(() => {
if (!keyParam) {
return hash({ fn, fnParams });
}
if (typeof keyParam !== 'string') {
return hash(keyParam);
}
return keyParam;
})()}`;
key = `${pluginName}:${key}`;
await cache.del(key);
};
module.exports = {
cache,
save,
getOrExec,
drop,
get,
};