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.
package/.npmignore CHANGED
@@ -3,3 +3,4 @@ coverage
3
3
  .idea
4
4
  *.iml
5
5
  out
6
+ .vscode
package/History.md CHANGED
@@ -1,3 +1,18 @@
1
+ - 2.9.0 2018-03-26
2
+ - Fix store's this context for isCacheableValue method (#119). -@alexandrusavin
3
+
4
+ - 2.8.0 2018-02-28
5
+ - Added link to node-cache-manager-fs-hash - @rolandstarke
6
+ - Bugfix for options object in multiCache.set (#115) - @sebelga
7
+ - Bugfix for keysToFetch in getFromHighestProrityCache (#117) - @sebelga
8
+
9
+ - 2.7.0 2018-02-13
10
+ - allow setting, getting and deleting multiple keys (#114) - @sebelga
11
+ - allow passing in a function to determine TTL based on store - @sebelga
12
+
13
+ - 2.6.0 2017-12-08
14
+ - fix multicaching when result is not cacheable (#106) - @gswalden
15
+
1
16
  - 2.5.0 2017-10-09
2
17
  - Add explicit return in wrapPromise (#109) - @jeff-kilbride
3
18
 
package/README.md CHANGED
@@ -43,6 +43,8 @@ See the [Express.js cache-manager example app](https://github.com/BryanDonovan/n
43
43
 
44
44
  * [node-cache-manager-fs-binary](https://github.com/sheershoff/node-cache-manager-fs-binary)
45
45
 
46
+ * [node-cache-manager-fs-hash](https://github.com/rolandstarke/node-cache-manager-fs-hash)
47
+
46
48
  * [node-cache-manager-hazelcast](https://github.com/marudor/node-cache-manager-hazelcast)
47
49
 
48
50
  * [node-cache-manager-memcached-store](https://github.com/theogravity/node-cache-manager-memcached-store)
@@ -51,7 +53,7 @@ See the [Express.js cache-manager example app](https://github.com/BryanDonovan/n
51
53
 
52
54
  ## Overview
53
55
 
54
- First, it includes a `wrap` function that lets you wrap any function in cache.
56
+ **First**, it includes a `wrap` function that lets you wrap any function in cache.
55
57
  (Note, this was inspired by [node-caching](https://github.com/mape/node-caching).)
56
58
  This is probably the feature you're looking for. As an example, where you might have to do this:
57
59
 
@@ -82,12 +84,14 @@ function getCachedUser(id, cb) {
82
84
  }
83
85
  ```
84
86
 
85
- Second, node-cache-manager features a built-in memory cache (using [node-lru-cache](https://github.com/isaacs/node-lru-cache)),
87
+ **Second**, node-cache-manager features a built-in memory cache (using [node-lru-cache](https://github.com/isaacs/node-lru-cache)),
86
88
  with the standard functions you'd expect in most caches:
87
89
 
88
90
  set(key, val, {ttl: ttl}, cb) // * see note below
89
91
  get(key, cb)
90
92
  del(key, cb)
93
+ mset(key1, val1, key2, val2, {ttl: ttl}, cb) // set several keys at once
94
+ mget(key1, key2, key3, cb) // get several keys at once
91
95
 
92
96
  // * Note that depending on the underlying store, you may be able to pass the
93
97
  // ttl as the third param, like this:
@@ -95,7 +99,7 @@ with the standard functions you'd expect in most caches:
95
99
  // ... or pass no ttl at all:
96
100
  set(key, val, cb)
97
101
 
98
- Third, node-cache-manager lets you set up a tiered cache strategy. This may be of
102
+ **Third**, node-cache-manager lets you set up a tiered cache strategy. This may be of
99
103
  limited use in most cases, but imagine a scenario where you expect tons of
100
104
  traffic, and don't want to hit your primary cache (like Redis) for every request.
101
105
  You decide to store the most commonly-requested data in an in-memory cache,
@@ -105,6 +109,8 @@ aren't as common as the ones you want to store in memory. This is something
105
109
  node-cache-manager handles easily and transparently.
106
110
 
107
111
 
112
+ **Fourth**, it allows you to get and set multiple keys at once for caching store that support it. This means that when getting muliple keys it will go through the different caches starting from the highest priority one (see multi store below) and merge the values it finds at each level.
113
+
108
114
  ## Usage Examples
109
115
 
110
116
  See examples below and in the examples directory. See ``examples/redis_example`` for an example of how to implement a
@@ -178,6 +184,41 @@ memoryCache.wrap(key, function(cb) {
178
184
  }
179
185
  ```
180
186
 
187
+ You can get several keys at once. E.g.
188
+
189
+ ```js
190
+
191
+ var key1 = 'user_1';
192
+ var key2 = 'user_1';
193
+
194
+ memoryCache.wrap(key1, key2, function (cb) {
195
+ getManyUser([key1, key2], cb);
196
+ }, function (err, users) {
197
+ console.log(users[0]);
198
+ console.log(users[1]);
199
+ });
200
+ ```
201
+
202
+ #### Example setting/getting several keys with mset() and mget()
203
+
204
+ ```js
205
+ memoryCache.mset('foo', 'bar', 'foo2', 'bar2' {ttl: ttl}, function(err) {
206
+ if (err) { throw err; }
207
+
208
+ memoryCache.mget('foo', 'foo2', function(err, result) {
209
+ console.log(result);
210
+ // >> ['bar', 'bar2']
211
+
212
+ // Delete keys with del() passing arguments...
213
+ memoryCache.del('foo', 'foo2', function(err) {});
214
+
215
+ // ...passing an Array of keys
216
+ memoryCache.del(['foo', 'foo2'], function(err) {});
217
+ });
218
+ });
219
+
220
+ ```
221
+
181
222
  #### Example Using Promises
182
223
 
183
224
  ```javascript
@@ -200,6 +241,22 @@ cache = caching({store: store, promiseDependency: Promise});
200
241
 
201
242
  ```
202
243
 
244
+ #### Example Using async/await
245
+
246
+ ```javascript
247
+
248
+ try {
249
+ let user = await memoryCache.wrap(key, function() {
250
+ return getUserPromise(userId);
251
+ });
252
+ } catch (err) {
253
+ // error handling
254
+ }
255
+ ```
256
+
257
+ Hint: should wrap `await` call with `try` - `catch` to handle `promise` error.
258
+
259
+
203
260
  #### Example Express App Usage
204
261
 
205
262
  (Also see the [Express.js cache-manager example app](https://github.com/BryanDonovan/node-cache-manager-express-example)).
@@ -246,6 +303,7 @@ key2 = 'user_' + userId;
246
303
  ttl = 5;
247
304
 
248
305
  // Sets in all caches.
306
+ // The "ttl" option can also be a function (see example below)
249
307
  multiCache.set('foo2', 'bar2', {ttl: ttl}, function(err) {
250
308
  if (err) { throw err; }
251
309
 
@@ -259,6 +317,38 @@ multiCache.set('foo2', 'bar2', {ttl: ttl}, function(err) {
259
317
  });
260
318
  });
261
319
 
320
+ // Set the ttl value by context depending on the store.
321
+ function getTTL(data, store) {
322
+ if (store === 'redis') {
323
+ return 6000;
324
+ }
325
+ return 3000;
326
+ }
327
+
328
+ // Sets multiple keys in all caches.
329
+ // You can pass as many key,value pair as you want
330
+ multiCache.mset('key', 'value', 'key2', 'value2', {ttl: getTTL}, function(err) {
331
+ if (err) { throw err; }
332
+
333
+ // mget() fetches from highest priority cache.
334
+ // If the first cache does not return all the keys,
335
+ // the next cache is fetched with the keys that were not found.
336
+ // This is done recursively until either:
337
+ // - all have been found
338
+ // - all caches has been fetched
339
+ multiCache.mget('key', 'key2', function(err, result) {
340
+ console.log(result[0]);
341
+ console.log(result[1]);
342
+ // >> 'bar2'
343
+ // >> 'bar3'
344
+
345
+ // Delete from all caches
346
+ multiCache.del('key', 'key2');
347
+ // ...or with an Array
348
+ multiCache.del(['key', 'key2']);
349
+ });
350
+ });
351
+
262
352
  // Note: options with ttl are optional in wrap()
263
353
  multiCache.wrap(key2, function (cb) {
264
354
  getUser(userId2, cb);
@@ -274,6 +364,14 @@ multiCache.wrap(key2, function (cb) {
274
364
  console.log(user);
275
365
  });
276
366
  });
367
+
368
+ // Multiple keys
369
+ multiCache.wrap('key1', 'key2', function (cb) {
370
+ getManyUser(['key1', 'key2'], cb);
371
+ }, {ttl: ttl}, function (err, users) {
372
+ console.log(users[0]);
373
+ console.log(users[1]);
374
+ });
277
375
  ```
278
376
 
279
377
  ### Specifying What to Cache in `wrap` Function
package/lib/caching.js CHANGED
@@ -1,6 +1,8 @@
1
1
  /** @module cacheManager/caching */
2
- /*jshint maxcomplexity:15*/
2
+ /*jshint maxcomplexity:16*/
3
3
  var CallbackFiller = require('./callback_filler');
4
+ var utils = require('./utils');
5
+ var parseWrapArguments = utils.parseWrapArguments;
4
6
 
5
7
  /**
6
8
  * Generic caching interface that wraps any caching library with a compatible interface.
@@ -36,7 +38,7 @@ var caching = function(args) {
36
38
  if (typeof args.isCacheableValue === 'function') {
37
39
  self._isCacheableValue = args.isCacheableValue;
38
40
  } else if (typeof self.store.isCacheableValue === 'function') {
39
- self._isCacheableValue = self.store.isCacheableValue;
41
+ self._isCacheableValue = self.store.isCacheableValue.bind(self.store);
40
42
  } else {
41
43
  self._isCacheableValue = function(value) {
42
44
  return value !== undefined;
@@ -47,12 +49,12 @@ var caching = function(args) {
47
49
  return new Promise(function(resolve, reject) {
48
50
  self.wrap(key, function(cb) {
49
51
  Promise.resolve()
50
- .then(promise)
51
- .then(function(result) {
52
- cb(null, result);
53
- return null;
54
- })
55
- .catch(cb);
52
+ .then(promise)
53
+ .then(function(result) {
54
+ cb(null, result);
55
+ return null;
56
+ })
57
+ .catch(cb);
56
58
  }, options, function(err, result) {
57
59
  if (err) {
58
60
  return reject(err);
@@ -66,33 +68,57 @@ var caching = function(args) {
66
68
  * Wraps a function in cache. I.e., the first time the function is run,
67
69
  * its results are stored in cache so subsequent calls retrieve from cache
68
70
  * instead of calling the function.
71
+ * You can pass any number of keys as long as the wrapped function returns
72
+ * an array with the same number of values and in the same order.
69
73
  *
70
74
  * @function
71
75
  * @name wrap
72
76
  *
73
- * @param {string} key - The cache key to use in cache operations
77
+ * @param {string} key - The cache key to use in cache operations. Can be one or many.
74
78
  * @param {function} work - The function to wrap
75
79
  * @param {object} [options] - options passed to `set` function
76
80
  * @param {function} cb
77
81
  *
78
82
  * @example
79
- * var key = 'user_' + userId;
80
- * cache.wrap(key, function(cb) {
81
- * User.get(userId, cb);
82
- * }, function(err, user) {
83
- * console.log(user);
84
- * });
83
+ * var key = 'user_' + userId;
84
+ * cache.wrap(key, function(cb) {
85
+ * User.get(userId, cb);
86
+ * }, function(err, user) {
87
+ * console.log(user);
88
+ * });
89
+ *
90
+ * // Multiple keys
91
+ * var key = 'user_' + userId;
92
+ * var key2 = 'user_' + userId2;
93
+ * cache.wrap(key, key2, function(cb) {
94
+ * User.getMany([userId, userId2], cb);
95
+ * }, function(err, users) {
96
+ * console.log(users[0]);
97
+ * console.log(users[1]);
98
+ * });
85
99
  */
86
- self.wrap = function(key, work, options, cb) {
87
- if (typeof options === 'function') {
88
- cb = options;
89
- options = {};
90
- }
100
+ self.wrap = function() {
101
+ var parsedArgs = parseWrapArguments(Array.prototype.slice.apply(arguments));
102
+ var keys = parsedArgs.keys;
103
+ var work = parsedArgs.work;
104
+ var options = parsedArgs.options;
105
+ var cb = parsedArgs.cb;
91
106
 
92
107
  if (!cb) {
93
- return wrapPromise(key, work, options);
108
+ keys.push(work);
109
+ keys.push(options);
110
+ return wrapPromise.apply(this, keys);
111
+ }
112
+
113
+ if (keys.length > 1) {
114
+ /**
115
+ * Handle more than 1 key
116
+ */
117
+ return wrapMultiple(keys, work, options, cb);
94
118
  }
95
119
 
120
+ var key = keys[0];
121
+
96
122
  var hasKey = callbackFiller.has(key);
97
123
  callbackFiller.add(key, {cb: cb});
98
124
  if (hasKey) { return; }
@@ -130,6 +156,85 @@ var caching = function(args) {
130
156
  });
131
157
  };
132
158
 
159
+ function wrapMultiple(keys, work, options, cb) {
160
+ /**
161
+ * We create a unique key for the multiple keys
162
+ * by concatenating them
163
+ */
164
+ var combinedKey = keys.reduce(function(acc, k) {
165
+ return acc + k;
166
+ }, '');
167
+
168
+ var hasKey = callbackFiller.has(combinedKey);
169
+ callbackFiller.add(combinedKey, {cb: cb});
170
+ if (hasKey) { return; }
171
+
172
+ keys.push(options);
173
+ keys.push(onResult);
174
+
175
+ self.store.mget.apply(self.store, keys);
176
+
177
+ function onResult(err, result) {
178
+ if (err && (!self.ignoreCacheErrors)) {
179
+ return callbackFiller.fill(combinedKey, err);
180
+ }
181
+
182
+ /**
183
+ * If all the values returned are cacheable we don't need
184
+ * to call our "work" method and the values returned by the cache
185
+ * are valid. If one or more of the values is not cacheable
186
+ * the cache result is not valid.
187
+ */
188
+ var cacheOK = Array.isArray(result) && result.filter(function(_result) {
189
+ return self._isCacheableValue(_result);
190
+ }).length === result.length;
191
+
192
+ if (cacheOK) {
193
+ return callbackFiller.fill(combinedKey, null, result);
194
+ }
195
+
196
+ return work(function(err, data) {
197
+ if (err) {
198
+ return done(err);
199
+ }
200
+
201
+ var _args = [];
202
+ data.forEach(function(value, i) {
203
+ /**
204
+ * Add the {key, value} pair to the args
205
+ * array that we will send to mset()
206
+ */
207
+ if (self._isCacheableValue(value)) {
208
+ _args.push(keys[i]);
209
+ _args.push(value);
210
+ }
211
+ });
212
+
213
+ // If no key|value, exit
214
+ if (_args.length === 0) {
215
+ return done(null);
216
+ }
217
+
218
+ if (options && typeof options.ttl === 'function') {
219
+ options.ttl = options.ttl(data);
220
+ }
221
+
222
+ _args.push(options);
223
+ _args.push(done);
224
+
225
+ self.store.mset.apply(self.store, _args);
226
+
227
+ function done(err) {
228
+ if (err && (!self.ignoreCacheErrors)) {
229
+ callbackFiller.fill(combinedKey, err);
230
+ } else {
231
+ callbackFiller.fill(combinedKey, null, data);
232
+ }
233
+ }
234
+ });
235
+ }
236
+ }
237
+
133
238
  /**
134
239
  * Binds to the underlying store's `get` function.
135
240
  * @function
@@ -137,6 +242,16 @@ var caching = function(args) {
137
242
  */
138
243
  self.get = self.store.get.bind(self.store);
139
244
 
245
+ /**
246
+ * Get multiple keys at once.
247
+ * Binds to the underlying store's `mget` function.
248
+ * @function
249
+ * @name mget
250
+ */
251
+ if (typeof self.store.mget === 'function') {
252
+ self.mget = self.store.mget.bind(self.store);
253
+ }
254
+
140
255
  /**
141
256
  * Binds to the underlying store's `set` function.
142
257
  * @function
@@ -144,6 +259,17 @@ var caching = function(args) {
144
259
  */
145
260
  self.set = self.store.set.bind(self.store);
146
261
 
262
+ /**
263
+ * Set multiple keys at once.
264
+ * It accepts any number of {key, value} pair
265
+ * Binds to the underlying store's `mset` function.
266
+ * @function
267
+ * @name mset
268
+ */
269
+ if (typeof self.store.mset === 'function') {
270
+ self.mset = self.store.mset.bind(self.store);
271
+ }
272
+
147
273
  /**
148
274
  * Binds to the underlying store's `del` function if it exists.
149
275
  * @function