-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (47 loc) · 1.36 KB
/
index.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
const pify = require('pify');
const redis = require('redis');
class MaybeStoreRedis {
constructor(opts = {}) {
this.ttlSupport = true;
this.namespace = opts.namespace || 'maybe-store';
const client = redis.createClient(opts);
this.redis = ['get', 'set', 'sadd', 'del', 'srem', 'smembers', 'quit'].reduce((obj, method) => {
obj[method] = pify(client[method]).bind(client);
return obj;
}, {});
}
_getNamespace() {
return `${this.namespace}:namespace`;
}
get(key) {
return this.redis.get(key).then(value => (value === null ? undefined : value));
}
set(key, value, ttl) {
if (value === undefined) {
return Promise.resolve();
}
return Promise.resolve()
.then(() => {
if (typeof ttl === 'number') {
return this.redis.set(key, value, 'PX', ttl);
}
return this.redis.set(key, value);
})
.then(() => this.redis.sadd(this._getNamespace(), key));
}
delete(key) {
return this.redis
.del(key)
.then(items => this.redis.srem(this._getNamespace(), key).then(() => items > 0));
}
clear() {
return this.redis
.smembers(this._getNamespace())
.then(keys => this.redis.del.apply(null, keys.concat(this._getNamespace())))
.then(() => undefined);
}
quit() {
return this.redis.quit();
}
}
module.exports = MaybeStoreRedis;