-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
121 lines (94 loc) · 2.67 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
const Redis = require('ioredis');
const redisStore = (...args) => {
let redisCache = null;
if (args.length > 0 && args[0].redisInstance) {
redisCache = args[0].redisInstance;
} else if (args.length > 0 && args[0].clusterConfig) {
const {
nodes,
options
} = args[0].clusterConfig;
redisCache = new Redis.Cluster(nodes, options || {});
} else {
redisCache = new Redis(...args);
}
const storeArgs = redisCache.options;
let self = {
name: 'redis',
isCacheableValue: storeArgs.isCacheableValue || (value => value !== undefined && value !== null),
};
self.getClient = () => redisCache;
self.set = (key, value, options, cb) => (
new Promise((resolve, reject) => {
if (typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
if (!cb) {
cb = (err, result) => (err ? reject(err) : resolve(result));
}
if (!self.isCacheableValue(value)) {
return cb(new Error(`"${value}" is not a cacheable value`));
}
const ttl = (options.ttl || options.ttl === 0) ? options.ttl : storeArgs.ttl;
const val = JSON.stringify(value) || '"undefined"';
if (ttl) {
redisCache.setex(key, ttl, val, handleResponse(cb));
} else {
redisCache.set(key, val, handleResponse(cb));
}
})
);
self.get = (key, options, cb) => (
new Promise((resolve, reject) => {
if (typeof options === 'function') {
cb = options;
}
if (!cb) {
cb = (err, result) => (err ? reject(err) : resolve(result));
}
redisCache.get(key, handleResponse(cb, { parse: true }));
})
);
self.del = (key, options, cb) => {
if (typeof options === 'function') {
cb = options;
}
redisCache.del(key, handleResponse(cb));
};
self.reset = cb => redisCache.flushdb(handleResponse(cb));
self.keys = (pattern, cb) => (
new Promise((resolve, reject) => {
if (typeof pattern === 'function') {
cb = pattern;
pattern = '*';
}
if (!cb) {
cb = (err, result) => (err ? reject(err) : resolve(result));
}
redisCache.keys(pattern, handleResponse(cb));
})
);
self.ttl = (key, cb) => redisCache.ttl(key, handleResponse(cb));
return self;
};
function handleResponse(cb, opts = {}) {
return (err, result) => {
if (err) {
return cb && cb(err);
}
if (opts.parse) {
try {
result = JSON.parse(result);
} catch (e) {
return cb && cb(e);
}
}
return cb && cb(null, result);
};
}
const methods = {
create: (...args) => redisStore(...args),
};
module.exports = methods;