cache-manager 2.5.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,9 @@
1
1
  /** @module cacheManager/multiCaching */
2
2
  var async = require('async');
3
3
  var CallbackFiller = require('./callback_filler');
4
+ var utils = require('./utils');
5
+ var isObject = utils.isObject;
6
+ var parseWrapArguments = utils.parseWrapArguments;
4
7
 
5
8
  /**
6
9
  * Module that lets you specify a hierarchy of caches.
@@ -48,25 +51,63 @@ var multiCaching = function(caches, options) {
48
51
  }
49
52
  }
50
53
 
51
- function getFromHighestPriorityCachePromise(key, options) {
54
+ function getFromHighestPriorityCachePromise() {
55
+ var args = Array.prototype.slice.apply(arguments).filter(function(v) {
56
+ return typeof v !== 'undefined';
57
+ });
58
+
52
59
  return new Promise(function(resolve, reject) {
53
- getFromHighestPriorityCache(key, options, function(err, result) {
60
+ var cb = function(err, result) {
54
61
  if (err) {
55
62
  return reject(err);
56
63
  }
57
64
  resolve(result);
58
- });
65
+ };
66
+ args.push(cb);
67
+ getFromHighestPriorityCache.apply(null, args);
59
68
  });
60
69
  }
61
70
 
62
- function getFromHighestPriorityCache(key, options, cb) {
63
- if (typeof options === 'function') {
64
- cb = options;
65
- options = {};
71
+ function getFromHighestPriorityCache() {
72
+ var args = Array.prototype.slice.apply(arguments).filter(function(v) {
73
+ return typeof v !== 'undefined';
74
+ });
75
+ var cb;
76
+ var options = {};
77
+
78
+ if (typeof args[args.length - 1] === 'function') {
79
+ cb = args.pop();
66
80
  }
67
81
 
68
82
  if (!cb) {
69
- return getFromHighestPriorityCachePromise(key, options);
83
+ return getFromHighestPriorityCachePromise.apply(this, args);
84
+ }
85
+
86
+ if (isObject(args[args.length - 1])) {
87
+ options = args.pop();
88
+ }
89
+
90
+ /**
91
+ * Keep a copy of the keys to retrieve
92
+ */
93
+ var keys = Array.prototype.slice.apply(args);
94
+ var multi = keys.length > 1;
95
+
96
+ /**
97
+ * Then put back the options in the args Array
98
+ */
99
+ args.push(options);
100
+
101
+ if (multi) {
102
+ /**
103
+ * Keep track of the keys left to fetch accross the caches
104
+ */
105
+ var keysToFetch = Array.prototype.slice.apply(keys);
106
+
107
+ /**
108
+ * Hash to save our multi keys result
109
+ */
110
+ var mapResult = {};
70
111
  }
71
112
 
72
113
  var i = 0;
@@ -78,7 +119,16 @@ var multiCaching = function(caches, options) {
78
119
 
79
120
  var _isCacheableValue = getIsCacheableValueFunction(cache);
80
121
 
81
- if (_isCacheableValue(result)) {
122
+ if (multi) {
123
+ addResultToMap(result, _isCacheableValue);
124
+
125
+ if (keysToFetch.length === 0 || i === caches.length - 1) {
126
+ // Return an Array with the values merged from all the caches
127
+ return cb(null, keys.map(function(k) {
128
+ return mapResult[k] || undefined;
129
+ }), i);
130
+ }
131
+ } else if (_isCacheableValue(result)) {
82
132
  // break out of async loop.
83
133
  return cb(err, result, i);
84
134
  }
@@ -87,37 +137,125 @@ var multiCaching = function(caches, options) {
87
137
  next();
88
138
  };
89
139
 
90
- cache.store.get(key, options, callback);
140
+ if (multi) {
141
+ if (typeof cache.store.mget !== 'function') {
142
+ /**
143
+ * Silently fail for store that don't support mget()
144
+ */
145
+ return callback(null, []);
146
+ }
147
+ var _args = Array.prototype.slice.apply(keysToFetch);
148
+ _args.push(options);
149
+ _args.push(callback);
150
+ cache.store.mget.apply(cache.store, _args);
151
+ } else {
152
+ cache.store.get(args[0], options, callback);
153
+ }
91
154
  }, function(err, result) {
92
155
  return cb(err, result);
93
156
  });
157
+
158
+ function addResultToMap(result, isCacheable) {
159
+ var key;
160
+ var diff = 0;
161
+
162
+ /**
163
+ * We loop through the result and if the value
164
+ * is cacheable we add it to the mapResult hash
165
+ * and remove the key to fetch from the "keysToFetch" array
166
+ */
167
+ result.forEach(function(res, i) {
168
+ if (isCacheable(res)) {
169
+ key = keysToFetch[i - diff];
170
+
171
+ // Add the result to our map
172
+ mapResult[key] = res;
173
+
174
+ // delete key from our keysToFetch array
175
+ keysToFetch.splice(i - diff, 1);
176
+ diff += 1;
177
+ }
178
+ });
179
+ }
94
180
  }
95
181
 
96
- function setInMultipleCachesPromise(caches, opts) {
182
+ function setInMultipleCachesPromise() {
183
+ var args = Array.prototype.slice.apply(arguments);
184
+
97
185
  return new Promise(function(resolve, reject) {
98
- setInMultipleCaches(caches, opts, function(err, result) {
186
+ var cb = function(err, result) {
99
187
  if (err) {
100
188
  return reject(err);
101
189
  }
102
190
  resolve(result);
103
- });
191
+ };
192
+ args.push(cb);
193
+ setInMultipleCaches.apply(null, args);
104
194
  });
105
195
  }
106
196
 
107
- function setInMultipleCaches(caches, opts, cb) {
108
- opts.options = opts.options || {};
197
+ function setInMultipleCaches() {
198
+ var args = Array.prototype.slice.apply(arguments);
199
+ var _caches = Array.isArray(args[0]) ? args.shift() : caches;
200
+
201
+ var cb;
202
+ var options = {};
203
+
204
+ if (typeof args[args.length - 1] === 'function') {
205
+ cb = args.pop();
206
+ }
109
207
 
110
208
  if (!cb) {
111
- return setInMultipleCachesPromise(caches, opts);
209
+ return setInMultipleCachesPromise.apply(this, args);
112
210
  }
113
211
 
114
- async.each(caches, function(cache, next) {
212
+ if (args.length % 2 > 0 && isObject(args[args.length - 1])) {
213
+ options = args.pop();
214
+ }
215
+
216
+ var length = args.length;
217
+ var multi = length > 2;
218
+ var i;
219
+
220
+ async.each(_caches, function(cache, next) {
115
221
  var _isCacheableValue = getIsCacheableValueFunction(cache);
222
+ var keysValues = Array.prototype.slice.apply(args);
223
+
224
+ /**
225
+ * We filter out the keys *not* cacheable
226
+ */
227
+ for (i = 0; i < length; i += 2) {
228
+ if (!_isCacheableValue(keysValues[i + 1])) {
229
+ keysValues.splice(i, 2);
230
+ }
231
+ }
116
232
 
117
- if (_isCacheableValue(opts.value)) {
118
- cache.store.set(opts.key, opts.value, opts.options, next);
233
+ if (keysValues.length === 0) {
234
+ return next();
235
+ }
236
+
237
+ var cacheOptions = options;
238
+ if (typeof options.ttl === 'function') {
239
+ /**
240
+ * Dynamically set the ttl by context depending of the store
241
+ */
242
+ cacheOptions = {};
243
+ cacheOptions.ttl = options.ttl(keysValues, cache.store.name);
244
+ }
245
+
246
+ if (multi) {
247
+ if (typeof cache.store.mset !== 'function') {
248
+ /**
249
+ * Silently fail for store that don't support mset()
250
+ */
251
+ return next();
252
+ }
253
+ keysValues.push(cacheOptions);
254
+ keysValues.push(next);
255
+
256
+ cache.store.mset.apply(cache.store, keysValues);
119
257
  } else {
120
- next();
258
+ cache.store.set(keysValues[0], keysValues[1], cacheOptions, next);
121
259
  }
122
260
  }, function(err, result) {
123
261
  cb(err, result);
@@ -194,30 +332,39 @@ var multiCaching = function(caches, options) {
194
332
  * without getting set in other lower-priority caches.
195
333
  * If a key doesn't exist in a higher-priority cache but exists in a lower-priority
196
334
  * cache, it gets set in all higher-priority caches.
335
+ * You can pass any number of keys as long as the wrapped function returns
336
+ * an array with the same number of values and in the same order.
337
+ *
338
+ * @function
339
+ * @name wrap
197
340
  *
198
- * @param {string} key - The cache key to use in cache operations
341
+ * @param {string} key - The cache key to use in cache operations. Can be one or many.
199
342
  * @param {function} work - The function to wrap
200
343
  * @param {object} [options] - options passed to `set` function
201
344
  * @param {function} cb
202
345
  */
203
- self.wrap = function(key, work, options, cb) {
204
- if (typeof options === 'function') {
205
- cb = options;
206
- options = {};
207
- }
346
+ self.wrap = function() {
347
+ var parsedArgs = parseWrapArguments(Array.prototype.slice.apply(arguments));
348
+ var keys = parsedArgs.keys;
349
+ var work = parsedArgs.work;
350
+ var options = parsedArgs.options;
351
+ var cb = parsedArgs.cb;
208
352
 
209
- function getOptsForSet(value) {
210
- return {
211
- key: key,
212
- value: value,
213
- options: options
214
- };
353
+ if (!cb) {
354
+ keys.push(work);
355
+ keys.push(options);
356
+ return wrapPromise.apply(this, keys);
215
357
  }
216
358
 
217
- if (!cb) {
218
- return wrapPromise(key, work, options);
359
+ if (keys.length > 1) {
360
+ /**
361
+ * Handle more than 1 key
362
+ */
363
+ return wrapMultiple(keys, work, options, cb);
219
364
  }
220
365
 
366
+ var key = keys[0];
367
+
221
368
  var hasKey = callbackFiller.has(key);
222
369
  callbackFiller.add(key, {cb: cb});
223
370
  if (hasKey) { return; }
@@ -227,11 +374,11 @@ var multiCaching = function(caches, options) {
227
374
  return callbackFiller.fill(key, err);
228
375
  } else if (self._isCacheableValue(result)) {
229
376
  var cachesToUpdate = caches.slice(0, index);
230
- var opts = getOptsForSet(result);
231
-
232
- setInMultipleCaches(cachesToUpdate, opts, function(err) {
377
+ var args = [cachesToUpdate, key, result, options, function(err) {
233
378
  callbackFiller.fill(key, err, result);
234
- });
379
+ }];
380
+
381
+ setInMultipleCaches.apply(null, args);
235
382
  } else {
236
383
  work(function(err, data) {
237
384
  if (err) {
@@ -239,19 +386,138 @@ var multiCaching = function(caches, options) {
239
386
  }
240
387
 
241
388
  if (!self._isCacheableValue(data)) {
242
- return cb();
389
+ return callbackFiller.fill(key, err, data);
243
390
  }
244
391
 
245
- var opts = getOptsForSet(data);
246
-
247
- setInMultipleCaches(caches, opts, function(err) {
392
+ var args = [caches, key, data, options, function(err) {
248
393
  callbackFiller.fill(key, err, data);
249
- });
394
+ }];
395
+
396
+ setInMultipleCaches.apply(null, args);
250
397
  });
251
398
  }
252
399
  });
253
400
  };
254
401
 
402
+ function wrapMultiple(keys, work, options, cb) {
403
+ /**
404
+ * We create a unique key for the multiple keys
405
+ * by concatenating them
406
+ */
407
+ var combinedKey = keys.reduce(function(acc, k) {
408
+ return acc + k;
409
+ }, '');
410
+
411
+ var hasKey = callbackFiller.has(combinedKey);
412
+ callbackFiller.add(combinedKey, {cb: cb});
413
+ if (hasKey) { return; }
414
+
415
+ keys.push(options);
416
+ keys.push(onResult);
417
+
418
+ /**
419
+ * Get from all the caches. If multiple keys have been passed,
420
+ * we'll go through all the caches and merge the result
421
+ */
422
+ getFromHighestPriorityCache.apply(this, keys);
423
+
424
+ function onResult(err, result, index) {
425
+ if (err) {
426
+ return done(err);
427
+ }
428
+
429
+ /**
430
+ * If all the values returned are cacheable we don't need
431
+ * to call our "work" method and the values returned by the cache
432
+ * are valid. If one or more of the values is not cacheable
433
+ * the cache result is not valid.
434
+ */
435
+ var cacheOK = result.filter(function(_result) {
436
+ return self._isCacheableValue(_result);
437
+ }).length === result.length;
438
+
439
+ if (!cacheOK) {
440
+ /**
441
+ * We need to fetch the data first
442
+ */
443
+ return work(workCallback);
444
+ }
445
+
446
+ var cachesToUpdate = caches.slice(0, index);
447
+
448
+ /**
449
+ * Prepare arguments to set the values in
450
+ * higher priority caches
451
+ */
452
+ var _args = [cachesToUpdate];
453
+
454
+ /**
455
+ * Add the {key, value} pair
456
+ */
457
+ result.forEach(function(value, i) {
458
+ _args.push(keys[i]);
459
+ _args.push(value);
460
+ });
461
+
462
+ /**
463
+ * Add options and final callback
464
+ */
465
+ _args.push(options);
466
+ _args.push(function(err) {
467
+ done(err, result);
468
+ });
469
+
470
+ return setInMultipleCaches.apply(null, _args);
471
+
472
+ /**
473
+ * Wrapped function callback
474
+ */
475
+ function workCallback(err, data) {
476
+ if (err) {
477
+ return done(err);
478
+ }
479
+
480
+ /**
481
+ * Prepare arguments for "setInMultipleCaches"
482
+ */
483
+ var _args;
484
+
485
+ _args = [];
486
+ data.forEach(function(value, i) {
487
+ /**
488
+ * Add the {key, value} pair to the args
489
+ * array that we will send to mset()
490
+ */
491
+ if (self._isCacheableValue(value)) {
492
+ _args.push(keys[i]);
493
+ _args.push(value);
494
+ }
495
+ });
496
+ // If no key,value --> exit
497
+ if (_args.length === 0) {
498
+ return done(null);
499
+ }
500
+
501
+ /**
502
+ * Add options and final callback
503
+ */
504
+ _args.push(options);
505
+ _args.push(function(err) {
506
+ done(err, data);
507
+ });
508
+
509
+ setInMultipleCaches.apply(null, _args);
510
+ }
511
+
512
+ /**
513
+ * Final callback
514
+ */
515
+ function done(err, data) {
516
+ callbackFiller.fill(combinedKey, err, data);
517
+ }
518
+ }
519
+ }
520
+
255
521
  /**
256
522
  * Set value in all caches
257
523
  *
@@ -263,20 +529,23 @@ var multiCaching = function(caches, options) {
263
529
  * @param {object} [options] to pass to underlying set function.
264
530
  * @param {function} [cb]
265
531
  */
266
- self.set = function(key, value, options, cb) {
267
- if (typeof options === 'function') {
268
- cb = options;
269
- options = {};
270
- }
532
+ self.set = setInMultipleCaches;
271
533
 
272
- var opts = {
273
- key: key,
274
- value: value,
275
- options: options
276
- };
277
-
278
- return setInMultipleCaches(caches, opts, cb);
279
- };
534
+ /**
535
+ * Set multiple values in all caches
536
+ * Accepts an unlimited pair of {key, value}
537
+ *
538
+ * @function
539
+ * @name mset
540
+ *
541
+ * @param {string} key
542
+ * @param {*} value
543
+ * @param {string} [key2]
544
+ * @param {*} [value2]
545
+ * @param {object} [options] to pass to underlying set function.
546
+ * @param {function} [cb]
547
+ */
548
+ self.mset = setInMultipleCaches;
280
549
 
281
550
  /**
282
551
  * Get value from highest level cache that has stored it.
@@ -288,14 +557,22 @@ var multiCaching = function(caches, options) {
288
557
  * @param {object} [options] to pass to underlying get function.
289
558
  * @param {function} cb
290
559
  */
291
- self.get = function(key, options, cb) {
292
- if (typeof options === 'function') {
293
- cb = options;
294
- options = {};
295
- }
560
+ self.get = getFromHighestPriorityCache;
296
561
 
297
- return getFromHighestPriorityCache(key, options, cb);
298
- };
562
+ /**
563
+ * Get multiple value from highest level cache that has stored it.
564
+ * If some values are not found, the next highest cache is used
565
+ * until either all keys are found or all caches have been fetched.
566
+ * Accepts an unlimited number of keys.
567
+ *
568
+ * @function
569
+ * @name mget
570
+ *
571
+ * @param {string} key key to get (any number)
572
+ * @param {object} [options] to pass to underlying get function.
573
+ * @param {function} cb optional callback
574
+ */
575
+ self.mget = getFromHighestPriorityCache;
299
576
 
300
577
  /**
301
578
  * Delete value from all caches.
@@ -307,14 +584,24 @@ var multiCaching = function(caches, options) {
307
584
  * @param {object} [options] to pass to underlying del function.
308
585
  * @param {function} cb
309
586
  */
310
- self.del = function(key, options, cb) {
311
- if (typeof options === 'function') {
312
- cb = options;
313
- options = {};
587
+ self.del = function() {
588
+ var args = Array.prototype.slice.apply(arguments);
589
+ var cb;
590
+ var options = {};
591
+
592
+ if (typeof args[args.length - 1] === 'function') {
593
+ cb = args.pop();
594
+ }
595
+
596
+ if (isObject(args[args.length - 1])) {
597
+ options = args.pop();
314
598
  }
315
599
 
600
+ args.push(options);
316
601
  async.each(caches, function(cache, next) {
317
- cache.store.del(key, options, next);
602
+ var _args = Array.prototype.slice.apply(args);
603
+ _args.push(next);
604
+ cache.store.del.apply(cache.store, _args);
318
605
  }, cb);
319
606
  };
320
607
 
@@ -1,4 +1,6 @@
1
1
  var Lru = require("lru-cache");
2
+ var utils = require('../utils');
3
+ var isObject = utils.isObject;
2
4
 
3
5
  var memoryStore = function(args) {
4
6
  args = args || {};
@@ -18,6 +20,16 @@ var memoryStore = function(args) {
18
20
 
19
21
  var lruCache = new Lru(lruOpts);
20
22
 
23
+ var setMultipleKeys = function setMultipleKeys(keysValues, maxAge) {
24
+ var length = keysValues.length;
25
+ var values = [];
26
+ for (var i = 0; i < length; i += 2) {
27
+ lruCache.set(keysValues[i], keysValues[i + 1], maxAge);
28
+ values.push(keysValues[i + 1]);
29
+ }
30
+ return values;
31
+ };
32
+
21
33
  self.set = function(key, value, options, cb) {
22
34
  if (typeof options === 'function') {
23
35
  cb = options;
@@ -35,6 +47,30 @@ var memoryStore = function(args) {
35
47
  }
36
48
  };
37
49
 
50
+ self.mset = function() {
51
+ var args = Array.prototype.slice.apply(arguments);
52
+ var cb;
53
+ var options = {};
54
+
55
+ if (typeof args[args.length - 1] === 'function') {
56
+ cb = args.pop();
57
+ }
58
+
59
+ if (args.length % 2 > 0 && isObject(args[args.length - 1])) {
60
+ options = args.pop();
61
+ }
62
+
63
+ var maxAge = (options.ttl || options.ttl === 0) ? options.ttl * 1000 : lruOpts.maxAge;
64
+
65
+ var values = setMultipleKeys(args, maxAge);
66
+
67
+ if (cb) {
68
+ process.nextTick(cb.bind(null, null));
69
+ } else if (self.usePromises) {
70
+ return Promise.resolve(values);
71
+ }
72
+ };
73
+
38
74
  self.get = function(key, options, cb) {
39
75
  if (typeof options === 'function') {
40
76
  cb = options;
@@ -50,12 +86,52 @@ var memoryStore = function(args) {
50
86
  }
51
87
  };
52
88
 
53
- self.del = function(key, options, cb) {
54
- if (typeof options === 'function') {
55
- cb = options;
89
+ self.mget = function() {
90
+ var args = Array.prototype.slice.apply(arguments);
91
+ var cb;
92
+ var options = {};
93
+
94
+ if (typeof args[args.length - 1] === 'function') {
95
+ cb = args.pop();
96
+ }
97
+
98
+ if (isObject(args[args.length - 1])) {
99
+ options = args.pop();
100
+ }
101
+
102
+ var values = args.map(function(key) {
103
+ return lruCache.get(key);
104
+ });
105
+
106
+ if (cb) {
107
+ process.nextTick(cb.bind(null, null, values));
108
+ } else if (self.usePromises) {
109
+ return Promise.resolve(values);
110
+ } else {
111
+ return values;
112
+ }
113
+ };
114
+
115
+ self.del = function() {
116
+ var args = Array.prototype.slice.apply(arguments);
117
+ var cb;
118
+ var options = {};
119
+
120
+ if (typeof args[args.length - 1] === 'function') {
121
+ cb = args.pop();
122
+ }
123
+
124
+ if (isObject(args[args.length - 1])) {
125
+ options = args.pop();
126
+ }
127
+
128
+ if (Array.isArray(args[0])) {
129
+ args = args[0];
56
130
  }
57
131
 
58
- lruCache.del(key);
132
+ args.forEach(function(key) {
133
+ lruCache.del(key);
134
+ });
59
135
 
60
136
  if (cb) {
61
137
  process.nextTick(cb.bind(null, null));
package/lib/utils.js ADDED
@@ -0,0 +1,43 @@
1
+
2
+ var isObject = function isObject(value) {
3
+ return value instanceof Object && value.constructor === Object;
4
+ };
5
+
6
+ var parseWrapArguments = function parseWrapArguments(args) {
7
+ var length = args.length;
8
+ var work;
9
+ var options = {};
10
+ var cb;
11
+
12
+ /**
13
+ * As we can receive an unlimited number of keys
14
+ * we find the index of the first function which is
15
+ * the "work" handler to fetch the keys.
16
+ */
17
+ for (var i = 0; i < length; i += 1) {
18
+ if (typeof args[i] === 'function') {
19
+ if (typeof args[i + 2] === 'function') {
20
+ cb = args.pop();
21
+ } else if (typeof args[i + 1] === 'function') {
22
+ cb = args.pop();
23
+ }
24
+ if (isObject(args[i + 1])) {
25
+ options = args.pop();
26
+ }
27
+ work = args.pop();
28
+ break;
29
+ }
30
+ }
31
+
32
+ return {
33
+ keys: args,
34
+ work: work,
35
+ options: options,
36
+ cb: cb
37
+ };
38
+ };
39
+
40
+ module.exports = {
41
+ isObject: isObject,
42
+ parseWrapArguments: parseWrapArguments,
43
+ };