-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
458 lines (403 loc) · 13.4 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
'use strict';
var RedisPool = require('sol-redis-pool');
var EventEmitter = require('events').EventEmitter;
var redisUrl = require('redis-url');
var zlib = require('zlib');
/**
* The cache manager Redis Store module
* @module redisStore
* @param {Object} [args] - The store configuration (optional)
* @param {String} args.host - The Redis server host
* @param {Number} args.port - The Redis server port
* @param {Number} args.db - The Redis server db
* @param {function} args.isCacheableValue - function to override built-in isCacheableValue function (optional)
* @param {boolean|Object} args.compress - (optional) Boolean / Config Object for pluggable compression.
* Setting this to true will use a default gzip configuration for best speed. Passing in a config
* object will forward those settings to the underlying compression implementation. Please see the
* Node zlib documentation for a list of valid options for gzip:
* https://nodejs.org/dist/latest-v4.x/docs/api/zlib.html#zlib_class_options
*/
function redisStore(args = {}) {
var self = {
name: 'redis',
events: new EventEmitter()
};
// cache-manager should always pass in args
/* istanbul ignore next */
var redisOptions = getFromUrl(args) || args;
var poolSettings = redisOptions;
var Promise = args.promiseDependency || global.Promise;
redisOptions.host = redisOptions.host || '127.0.0.1';
redisOptions.port = redisOptions.port || 6379;
redisOptions.db = redisOptions.db || 0;
// default compress config
redisOptions.detect_buffers = true;
var compressDefault = {
type: 'gzip',
params: {
level: zlib.Z_BEST_SPEED
}
};
// if compress is boolean true, set default
if (redisOptions.compress === true) {
redisOptions.compress = compressDefault;
}
var pool = new RedisPool(redisOptions, poolSettings);
pool.on('error', function(err) {
self.events.emit('redisError', err);
});
/**
* Helper to connect to a connection pool
* @private
* @param {Function} cb - A callback that returns
*/
function connect(cb) {
pool.acquireDb(cb, redisOptions.db);
}
/**
* Helper to handle callback and release the connection
* @private
* @param {Object} conn - The Redis connection
* @param {Function} [cb] - A callback that returns a potential error and the result
* @param {Object} [opts] - The options (optional)
*/
function handleResponse(conn, cb, opts) {
opts = opts || {};
return function(err, result) {
pool.release(conn);
if (err) {
return cb && cb(err);
}
if (opts.parse) {
if (result && opts.compress) {
return zlib.gunzip(result, opts.compress.params || {}, function (gzErr, gzResult) {
if (gzErr) {
return cb && cb(gzErr);
}
try {
gzResult = JSON.parse(gzResult);
} catch (e) {
return cb && cb(e);
}
return cb && cb(null, gzResult);
});
}
try {
result = JSON.parse(result);
} catch (e) {
return cb && cb(e);
}
}
return cb && cb(null, result);
};
}
/**
* Extracts options from an args.url
* @param {Object} args
* @param {String} args.url a string in format of redis://[:password@]host[:port][/db-number][?option=value]
* @returns {Object} the input object args if it is falsy, does not contain url or url is not string, otherwise a new object with own properties of args
* but with host, port, db, ttl and auth_pass properties overridden by those provided in args.url.
*/
function getFromUrl(args) {
if (!args || typeof args.url !== 'string') {
return args;
}
try {
var options = redisUrl.parse(args.url);
// make a clone so we don't change input args
return applyOptionsToArgs(args, options);
} catch (e) {
//url is unparsable so returning original
return args;
}
}
/**
* Clones args'es own properties to a new object and sets isCacheableValue on the new object
* @param {Object} args
* @returns {Object} a clone of the args object
*/
function cloneArgs(args) {
var newArgs = {};
for(var key in args){
if (key && args.hasOwnProperty(key)) {
newArgs[key] = args[key];
}
}
newArgs.isCacheableValue = args.isCacheableValue && args.isCacheableValue.bind(newArgs);
return newArgs;
}
/**
* Apply some options like hostname, port, db, ttl, auth_pass, password
* from options to newArgs host, port, db, auth_pass, password and ttl and return clone of args
* @param {Object} args
* @param {Object} options
* @returns {Object} clone of args param with properties set to those of options
*/
function applyOptionsToArgs(args, options) {
var newArgs = cloneArgs(args);
newArgs.host = options.hostname;
newArgs.port = parseInt(options.port, 10);
newArgs.db = parseInt(options.database, 10);
newArgs.auth_pass = options.password;
newArgs.password = options.password;
if(options.query && options.query.ttl){
newArgs.ttl = parseInt(options.query.ttl, 10);
}
return newArgs;
}
/**
* Get a value for a given key.
* @method get
* @param {String} key - The cache key
* @param {Object} [options] - The options (optional)
* @param {boolean|Object} options.compress - compression configuration
* @param {Function} cb - A callback that returns a potential error and the response
* @returns {Promise}
*/
self.get = function(key, options, cb) {
return new Promise(function(resolve, reject) {
if (typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
options.parse = true;
cb = cb ? cb : (err, result) => err ? reject(err) : resolve(result);
var compress = (options.compress || options.compress === false) ? options.compress : redisOptions.compress;
if (compress) {
options.compress = (compress === true) ? compressDefault : compress;
key = new Buffer(key);
}
connect(function(err, conn) {
if (err) {
return cb(err);
}
conn.get(key, handleResponse(conn, cb, options));
});
});
};
/**
* Set a value for a given key.
* @method set
* @param {String} key - The cache key
* @param {String} value - The value to set
* @param {Object} [options] - The options (optional)
* @param {Object} options.ttl - The ttl value
* @param {boolean|Object} options.compress - compression configuration
* @param {Function} [cb] - A callback that returns a potential error, otherwise null
* @returns {Promise}
*/
self.set = function(key, value, options, cb) {
options = options || {};
if (typeof options === 'function') {
cb = options;
options = {};
}
return new Promise(function(resolve, reject) {
cb = cb || ((err, result) => err ? reject(err) : resolve(result));
if (!self.isCacheableValue(value)) {
return cb(new Error('value cannot be ' + value));
}
var ttl = (options.ttl || options.ttl === 0) ? options.ttl : redisOptions.ttl;
var compress = (options.compress || options.compress === false) ? options.compress : redisOptions.compress;
if (compress === true) {
compress = compressDefault;
}
connect(function(err, conn) {
if (err) {
return cb(err);
}
var val = JSON.stringify(value) || '"undefined"';
// Refactored to remove duplicate code.
function persist(pErr, pVal) {
if (pErr) {
return cb(pErr);
}
if (ttl) {
conn.setex(key, ttl, pVal, handleResponse(conn, cb));
} else {
conn.set(key, pVal, handleResponse(conn, cb));
}
}
if (compress) {
zlib.gzip(val, compress.params || {}, persist);
} else {
persist(null, val);
}
});
});
};
/**
* Delete value of a given key
* @method del
* @param {String|Array} key - The cache key or array of keys to delete
* @param {Object} [options] - The options (optional)
* @param {Function} [cb] - A callback that returns a potential error, otherwise null
* @returns {Promise}
*/
self.del = function(key, options, cb) {
return new Promise((resolve, reject) => {
cb = cb || ((err) => err ? reject(err) : resolve('OK'));
if (typeof options === 'function') {
cb = options;
options = {};
}
connect(function(err, conn) {
if (err) {
return cb(err);
}
if (Array.isArray(key)) {
var multi = conn.multi();
for (var i = 0, l = key.length; i < l; ++i) {
multi.del(key[i]);
}
multi.exec(handleResponse(conn, cb));
}
else {
conn.del(key, handleResponse(conn, cb));
}
});
});
};
/**
* Delete all the keys of the currently selected DB
* @method reset
* @param {Function} [cb] - A callback that returns a potential error, otherwise null
* @returns {Promise}
*/
self.reset = function(cb) {
return new Promise((resolve, reject) => {
cb = cb || (err => err ? reject(err) : resolve('OK'));
connect(function(err, conn) {
if (err) {
return cb(err);
}
conn.flushdb(handleResponse(conn, cb));
});
});
};
/**
* Returns the remaining time to live of a key that has a timeout.
* @method ttl
* @param {String} key - The cache key
* @param {Function} cb - A callback that returns a potential error and the response
* @returns {Promise}
*/
self.ttl = function(key, cb) {
return new Promise((resolve, reject) => {
cb = cb || ((err, res) => err ? reject(err) : resolve(res));
connect(function(err, conn) {
if (err) {
return cb(err);
}
conn.ttl(key, handleResponse(conn, cb));
});
});
};
/**
* Returns all keys matching pattern using the SCAN command.
* @method keys
* @param {String} [pattern] - The pattern used to match keys (default: *)
* @param {Object} [options] - The options (default: {})
* @param {number} [options.scanCount] - The number of keys to traverse with each call to SCAN (default: 100)
* @param {Function} cb - A callback that returns a potential error and the response
* @returns {Promise}
*/
self.keys = function(pattern, options, cb) {
options = options || {};
// Account for all argument permutations.
// Only cb supplied.
if (typeof pattern === 'function') {
cb = pattern;
options = {};
pattern = '*';
}
// options and cb supplied.
else if (typeof pattern === 'object') {
cb = options;
options = pattern;
pattern = '*';
}
// pattern and cb supplied.
else if (typeof options === 'function') {
cb = options;
options = {};
}
return new Promise((resolve, reject) => {
cb = cb || ((err, res) => err ? reject(err) : resolve(res));
connect(function(err, conn) {
if (err) {
return cb(err);
}
// Use an object to dedupe as scan can return duplicates
var keysObj = {};
var scanCount = Number(options.scanCount) || 100;
(function nextBatch(cursorId) {
conn.scan(cursorId, 'match', pattern, 'count', scanCount, function (err, result) {
if (err) {
handleResponse(conn, cb)(err);
}
var nextCursorId = result[0];
var keys = result[1];
for (var i = 0, l = keys.length; i < l; ++i) {
keysObj[keys[i]] = 1;
}
if (nextCursorId !== '0') {
return nextBatch(nextCursorId);
}
handleResponse(conn, cb)(null, Object.keys(keysObj));
});
})(0);
});
});
};
/**
* Specify which values should and should not be cached.
* If the function returns true, it will be stored in cache.
* By default, it caches everything except undefined and null values.
* Can be overriden via standard node-cache-manager options.
* @method isCacheableValue
* @param {String} value - The value to check
* @return {Boolean} - Returns true if the value is cacheable, otherwise false.
*/
self.isCacheableValue = args.isCacheableValue || function(value) {
return value !== undefined && value !== null;
};
/**
* Returns the underlying redis client connection
* @method getClient
* @param {Function} cb - A callback that returns a potential error and an object containing the Redis client and a done method
* @returns {Promise}
*/
self.getClient = function(cb) {
return new Promise((resolve, reject) => {
cb = cb || ((err, res) => err ? reject(err) : resolve(res));
connect(function(err, conn) {
if (err) {
return cb(err);
}
cb(null, {
client: conn,
done: function(done) {
var args = Array.prototype.slice.call(arguments, 1);
pool.release(conn);
if (done && typeof done === 'function') {
done.apply(null, args);
}
}
});
});
});
};
/**
* Expose the raw pool object for testing purposes
* @private
*/
self._pool = pool;
return self;
}
module.exports = {
create: function(args) {
return redisStore(args);
}
};