-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.js
60 lines (49 loc) · 1.51 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
const debug = require('debug');
/**
* node-cache的缓存类, 参数模仿ioredis
* 只支持 get set del 方法
*/
class Cache {
constructor(instance) {
this.type = 'node';
this.instance = instance;
this.debug = debug(`Cache:${this.type}`);
this.debug('new instance');
}
//perform get, returns saved data or null
get(key) {
this.debug('get', key);
return Promise.resolve(this.instance.get(key)).then(r => r === undefined ? null : r);
}
//perform set, returns bool
//supports NX
set(key, val, PXEX, expires, NXXX) {
this.debug('set', key, val, PXEX || '', expires || '', NXXX || '');
if (PXEX === 'NX' || PXEX === 'XX') {
NXXX = PXEX;
PXEX = null;
expires = 0;
}
let expireSeconds = 0;
if (PXEX === 'EX') expireSeconds = expires;
if (PXEX === 'PX') expireSeconds = expires / 1000;
this.debug('nodecache.set', key, val, PXEX, `${expires}(seconds=${expireSeconds})`, NXXX);
if (NXXX === 'NX') {
let old = this.instance.get(key);
if (old) return Promise.resolve(false);
return Promise.resolve(!!this.instance.set(key, val, expireSeconds));
} else if (NXXX === 'XX') {
let old = this.instance.get(key);
if (old === undefined) return Promise.resolve(false);
return Promise.resolve(!!this.instance.set(key, val, expireSeconds));
} else {
return Promise.resolve(!!this.instance.set(key, val, expireSeconds));
}
}
//perform delelete, returns bool
del(key) {
this.debug('del', key);
return Promise.resolve(!!this.instance.del(key));
}
}
module.exports = Cache;