forked from dabroek/node-cache-manager-ioredis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
106 lines (88 loc) · 2.47 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
import Redis from 'ioredis';
const redisStore = (...args) => {
let redisCache = null;
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;
return {
name: 'redis',
getClient: () => redisCache,
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));
}
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));
}
})
),
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 }));
})
),
del: (key, options, cb) => {
if (typeof options === 'function') {
cb = options;
}
redisCache.del(key, handleResponse(cb));
},
reset: cb => redisCache.flushdb(handleResponse(cb)),
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));
})
),
ttl: (key, cb) => redisCache.ttl(key, handleResponse(cb)),
isCacheableValue: storeArgs.isCacheableValue || (value => value !== undefined && value !== null),
};
};
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),
};
export default methods;