cache-utils.js
1.19 KB
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
const cache = global.yoho.cache;
const logger = global.yoho.logger;
const ONE_MINUTE = 60;
const FIVE_MINUTE = 5 * ONE_MINUTE;
function _cacheGet(key) {
return cache.get(key).then((data) => {
if (data) {
return JSON.parse(data);
}
return Promise.reject();
});
}
function _cacheSave(key, value, ttl) {
return cache.set(key, value, ttl)
.catch(err => logger.error(`save cache data fail:${err.toString()}`));
}
function defaultKey() {
const args = Array.prototype.slice.call(arguments);
return JSON.stringify(args || '[]');
}
function _cached(fn, keyFn = defaultKey, ctx = null, ttl = FIVE_MINUTE) {
const keyGen = function() {
const args = Array.prototype.slice.call(arguments);
return '_cache:' + (fn.name || '') + ':' + keyFn.apply(null, args);
};
return function() {
const args = Array.prototype.slice.call(arguments);
const key = keyGen.apply(null, args);
return _cacheGet(key).catch(() => {
return fn.apply(ctx, args).then(result => {
_cacheSave(key, result, ttl);
return result;
});
});
};
}
module.exports = _cached;