cache-manager 4.1.0 → 5.0.1

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/README.md CHANGED
@@ -1,484 +1,59 @@
1
- [![build status](https://secure.travis-ci.org/BryanDonovan/node-cache-manager.svg)](http://travis-ci.org/BryanDonovan/node-cache-manager)
2
- [![Coverage Status](https://coveralls.io/repos/BryanDonovan/node-cache-manager/badge.svg?branch=master)](https://coveralls.io/r/BryanDonovan/node-cache-manager?branch=master)
3
-
4
- node-cache-manager
5
- ======================
1
+ # node-cache-manager [![npm version](https://badge.fury.io/js/cache-manager.svg)](https://www.npmjs.com/package/cache-manager) [![codecov](https://codecov.io/gh/node-cache-manager/node-cache-manager/branch/master/graph/badge.svg?token=ZV3G5IFigq)](https://codecov.io/gh/node-cache-manager/node-cache-manager)
6
2
 
7
3
  # Flexible NodeJS cache module
8
4
 
9
- A cache module for nodejs that allows easy wrapping of functions in cache,
10
- tiered caches, and a consistent interface.
5
+ A cache module for nodejs that allows easy wrapping of functions in cache, tiered caches, and a consistent interface.
11
6
 
12
7
  ## Features
13
8
 
14
- * Easy way to wrap any function in cache.
15
- * Tiered caches -- data gets stored in each cache and fetched from the highest
16
- priority cache(s) first.
17
- * Use any cache you want, as long as it has the same API.
18
- * 100% test coverage via [mocha](https://github.com/visionmedia/mocha),
19
- [istanbul](https://github.com/yahoo/istanbul), and [sinon](http://sinonjs.org).
20
-
9
+ - Easy way to wrap any function in cache.
10
+ - Tiered caches -- data gets stored in each cache and fetched from the highest.
11
+ priority cache(s) first.
12
+ - Use any cache you want, as long as it has the same API.
13
+ - 100% test coverage via [vitest](https://github.com/vitest-dev/vitest).
21
14
 
22
15
  ## Express.js Example
23
16
 
24
17
  See the [Express.js cache-manager example app](https://github.com/BryanDonovan/node-cache-manager-express-example) to see how to use
25
- ``node-cache-manager`` in your applications.
18
+ `node-cache-manager` in your applications.
26
19
 
27
20
  ## Installation
28
21
 
29
- npm install cache-manager
22
+ pnpm install cache-manager
30
23
 
31
24
  ## Store Engines
32
- * [node-cache-manager-redis](https://github.com/dial-once/node-cache-manager-redis) (uses [sol-redis-pool](https://github.com/joshuah/sol-redis-pool))
33
-
34
- * [node-cache-manager-redis-store](https://github.com/dabroek/node-cache-manager-redis-store) (uses [node_redis](https://github.com/NodeRedis/node_redis))
35
-
36
- * [node-cache-manager-ioredis](https://github.com/dabroek/node-cache-manager-ioredis) (uses [ioredis](https://github.com/luin/ioredis))
37
-
38
- * [node-cache-manager-mongodb](https://github.com/v4l3r10/node-cache-manager-mongodb)
39
-
40
- * [node-cache-manager-mongoose](https://github.com/disjunction/node-cache-manager-mongoose)
41
-
42
- * [node-cache-manager-fs-binary](https://github.com/sheershoff/node-cache-manager-fs-binary)
43
-
44
- * [node-cache-manager-fs-hash](https://github.com/rolandstarke/node-cache-manager-fs-hash)
45
-
46
- * [node-cache-manager-hazelcast](https://github.com/marudor/node-cache-manager-hazelcast)
47
-
48
- * [node-cache-manager-memcached-store](https://github.com/theogravity/node-cache-manager-memcached-store)
49
-
50
- * [node-cache-manager-memory-store](https://github.com/theogravity/node-cache-manager-memory-store)
51
-
52
- * [node-cache-manager-couchbase](https://github.com/davidepellegatta/node-cache-manager-couchbase)
53
-
54
- ## Overview
55
-
56
- **First**, it includes a `wrap` function that lets you wrap any function in cache.
57
- (Note, this was inspired by [node-caching](https://github.com/mape/node-caching).)
58
- This is probably the feature you're looking for. As an example, where you might have to do this:
59
-
60
- ```javascript
61
- function getCachedUser(id, cb) {
62
- memoryCache.get(id, function (err, result) {
63
- if (err) { return cb(err); }
64
-
65
- if (result) {
66
- return cb(null, result);
67
- }
68
-
69
- getUser(id, function (err, result) {
70
- if (err) { return cb(err); }
71
- memoryCache.set(id, result);
72
- cb(null, result);
73
- });
74
- });
75
- }
76
- ```
77
- ... you can instead use the `wrap` function:
78
-
79
- ```javascript
80
- function getCachedUser(id, cb) {
81
- memoryCache.wrap(id, function (cacheCallback) {
82
- getUser(id, cacheCallback);
83
- }, {ttl: ttl}, cb);
84
- }
85
- ```
86
-
87
- **Second**, node-cache-manager features a built-in memory cache (using [node-lru-cache](https://github.com/isaacs/node-lru-cache)),
88
- with the standard functions you'd expect in most caches:
89
-
90
- set(key, val, {ttl: ttl}, cb) // * see note below
91
- get(key, cb)
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
95
-
96
- // * Note that depending on the underlying store, you may be able to pass the
97
- // ttl as the third param, like this:
98
- set(key, val, ttl, cb)
99
- // ... or pass no ttl at all:
100
- set(key, val, cb)
101
-
102
- **Third**, node-cache-manager lets you set up a tiered cache strategy. This may be of
103
- limited use in most cases, but imagine a scenario where you expect tons of
104
- traffic, and don't want to hit your primary cache (like Redis) for every request.
105
- You decide to store the most commonly-requested data in an in-memory cache,
106
- perhaps with a very short timeout and/or a small data size limit. But you
107
- still want to store the data in Redis for backup, and for the requests that
108
- aren't as common as the ones you want to store in memory. This is something
109
- node-cache-manager handles easily and transparently.
110
-
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
-
114
- ## Usage Examples
115
-
116
- See examples below and in the examples directory. See ``examples/redis_example`` for an example of how to implement a
117
- Redis cache store with connection pooling.
118
-
119
- ### Single Store
120
-
121
- ```javascript
122
- var cacheManager = require('cache-manager');
123
- var memoryCache = cacheManager.caching({store: 'memory', max: 100, ttl: 10/*seconds*/});
124
- var ttl = 5;
125
- // Note: callback is optional in set() and del().
126
- // Note: memory cache clones values before setting them unless
127
- // shouldCloneBeforeSet is set to false
128
-
129
- memoryCache.set('foo', 'bar', {ttl: ttl}, function(err) {
130
- if (err) { throw err; }
131
-
132
- memoryCache.get('foo', function(err, result) {
133
- console.log(result);
134
- // >> 'bar'
135
- memoryCache.del('foo', function(err) {});
136
- });
137
- });
138
-
139
- function getUser(id, cb) {
140
- setTimeout(function () {
141
- console.log("Returning user from slow database.");
142
- cb(null, {id: id, name: 'Bob'});
143
- }, 100);
144
- }
145
-
146
- var userId = 123;
147
- var key = 'user_' + userId;
148
-
149
- // Note: ttl is optional in wrap()
150
- memoryCache.wrap(key, function (cb) {
151
- getUser(userId, cb);
152
- }, {ttl: ttl}, function (err, user) {
153
- console.log(user);
154
-
155
- // Second time fetches user from memoryCache
156
- memoryCache.wrap(key, function (cb) {
157
- getUser(userId, cb);
158
- }, function (err, user) {
159
- console.log(user);
160
- });
161
- });
162
-
163
- // Outputs:
164
- // Returning user from slow database.
165
- // { id: 123, name: 'Bob' }
166
- // { id: 123, name: 'Bob' }
167
- ```
168
-
169
- The `ttl` can also be computed dynamically by passing in a function. E.g.,
170
-
171
- ```javascript
172
- var opts = {
173
- ttl: function(user) {
174
- if (user.id === 1) {
175
- return 0.1;
176
- } else {
177
- return 0.5;
178
- }
179
- }
180
- };
181
-
182
- memoryCache.wrap(key, function(cb) {
183
- getUser(userId, cb);
184
- }, opts, function(err, user) {
185
- console.log(user);
186
- }
187
- ```
188
-
189
- You can get several keys at once. Note that this will return whatever records it
190
- finds in the cache and it is up to the user to check the results against the
191
- supplied keys and make any calls to the underlying data store to fill in
192
- missing records. In practice, this should not be much of a concern if you are
193
- only using the `wrap` function to set these records in cache.
194
-
195
- Side note: Ideally the `wrap` function would get what it can from the cache and fill in
196
- the missing records from the data store, but I can't think of a way to do this
197
- that is generic to all situations. Another option is to only return the data
198
- from the cache if all records are found, but this woul break multi-caching.
199
-
200
- See unit tests in `caching.unit.js` for more information.
201
-
202
- Example:
203
-
204
- ```js
205
-
206
- var key1 = 'user_1';
207
- var key2 = 'user_1';
208
-
209
- memoryCache.wrap(key1, key2, function (cb) {
210
- getManyUser([key1, key2], cb);
211
- }, function (err, users) {
212
- console.log(users[0]);
213
- console.log(users[1]);
214
- });
215
- ```
216
-
217
- #### Example setting/getting several keys with mset() and mget()
218
-
219
- ```js
220
- memoryCache.mset('foo', 'bar', 'foo2', 'bar2', {ttl: ttl}, function(err) {
221
- if (err) { throw err; }
222
-
223
- memoryCache.mget('foo', 'foo2', function(err, result) {
224
- console.log(result);
225
- // >> ['bar', 'bar2']
226
-
227
- // Delete keys with del() passing arguments...
228
- memoryCache.del('foo', 'foo2', function(err) {});
229
-
230
- // ...passing an Array of keys
231
- memoryCache.del(['foo', 'foo2'], function(err) {});
232
- });
233
- });
234
-
235
- ```
236
-
237
- #### Example Using Promises
238
-
239
- ```javascript
240
- memoryCache.wrap(key, function() {
241
- return getUserPromise(userId);
242
- })
243
- .then(function(user) {
244
- console.log('User:', user);
245
- });
246
- ```
247
25
 
248
- If you are using a Node version that does not include native promises, you can
249
- specify your promise dependency in the options passed to the cache module.
250
- E.g.,
26
+ - [node-cache-manager-redis](https://github.com/dial-once/node-cache-manager-redis) (uses [sol-redis-pool](https://github.com/joshuah/sol-redis-pool))
251
27
 
252
- ```javascript
28
+ - [node-cache-manager-redis-store](https://github.com/dabroek/node-cache-manager-redis-store) (uses [node_redis](https://github.com/NodeRedis/node_redis))
253
29
 
254
- var Promise = require('es6-promise').Promise;
255
- cache = caching({store: store, promiseDependency: Promise});
30
+ - [node-cache-manager-ioredis](https://github.com/dabroek/node-cache-manager-ioredis) (uses [ioredis](https://github.com/luin/ioredis))
256
31
 
257
- ```
32
+ - [node-cache-manager-redis-yet](https://github.com/node-cache-manager/node-cache-manager-redis-yet) (uses [node_redis](https://github.com/NodeRedis/node_redis))
258
33
 
259
- #### Example Using async/await
34
+ - [node-cache-manager-mongodb](https://github.com/v4l3r10/node-cache-manager-mongodb)
260
35
 
261
- ```javascript
36
+ - [node-cache-manager-mongoose](https://github.com/disjunction/node-cache-manager-mongoose)
262
37
 
263
- try {
264
- let user = await memoryCache.wrap(key, function() {
265
- return getUserPromise(userId);
266
- });
267
- } catch (err) {
268
- // error handling
269
- }
270
- ```
38
+ - [node-cache-manager-fs-binary](https://github.com/sheershoff/node-cache-manager-fs-binary)
271
39
 
272
- Hint: should wrap `await` call with `try` - `catch` to handle `promise` error.
40
+ - [node-cache-manager-fs-hash](https://github.com/rolandstarke/node-cache-manager-fs-hash)
273
41
 
42
+ - [node-cache-manager-hazelcast](https://github.com/marudor/node-cache-manager-hazelcast)
274
43
 
275
- #### Example Express App Usage
44
+ - [node-cache-manager-memcached-store](https://github.com/theogravity/node-cache-manager-memcached-store)
276
45
 
277
- (Also see the [Express.js cache-manager example app](https://github.com/BryanDonovan/node-cache-manager-express-example)).
46
+ - [node-cache-manager-memory-store](https://github.com/theogravity/node-cache-manager-memory-store)
278
47
 
279
- ```javascript
280
- function respond(res, err, data) {
281
- if (err) {
282
- res.json(500, err);
283
- } else {
284
- res.json(200, data);
285
- }
286
- }
287
-
288
- app.get('/foo/bar', function(req, res) {
289
- var cacheKey = 'foo-bar:' + JSON.stringify(req.query);
290
- var ttl = 10;
291
- memoryCache.wrap(cacheKey, function(cacheCallback) {
292
- DB.find(req.query, cacheCallback);
293
- }, {ttl: ttl}, function(err, result) {
294
- respond(res, err, result);
295
- });
296
- });
297
- ```
298
-
299
- #### Custom Stores
300
-
301
- You can use your own custom store by creating one with the same API as the
302
- built-in memory stores (such as a redis or memcached store). To use your own store just pass
303
- in an instance of it.
304
-
305
- E.g.,
306
-
307
- ```javascript
308
- var myStore = require('your-homemade-store');
309
- var cache = cacheManager.caching({store: myStore});
310
- ```
311
-
312
- ### Multi-Store
313
-
314
- ```javascript
315
- var multiCache = cacheManager.multiCaching([memoryCache, someOtherCache]);
316
- userId2 = 456;
317
- key2 = 'user_' + userId;
318
- ttl = 5;
319
-
320
- // Sets in all caches.
321
- // The "ttl" option can also be a function (see example below)
322
- multiCache.set('foo2', 'bar2', {ttl: ttl}, function(err) {
323
- if (err) { throw err; }
324
-
325
- // Fetches from highest priority cache that has the key.
326
- multiCache.get('foo2', function(err, result) {
327
- console.log(result);
328
- // >> 'bar2'
329
-
330
- // Delete from all caches
331
- multiCache.del('foo2');
332
- });
333
- });
334
-
335
- // Set the ttl value by context depending on the store.
336
- function getTTL(data, store) {
337
- if (store === 'redis') {
338
- return 6000;
339
- }
340
- return 3000;
341
- }
342
-
343
- // Sets multiple keys in all caches.
344
- // You can pass as many key,value pair as you want
345
- multiCache.mset('key', 'value', 'key2', 'value2', {ttl: getTTL}, function(err) {
346
- if (err) { throw err; }
347
-
348
- // mget() fetches from highest priority cache.
349
- // If the first cache does not return all the keys,
350
- // the next cache is fetched with the keys that were not found.
351
- // This is done recursively until either:
352
- // - all have been found
353
- // - all caches has been fetched
354
- multiCache.mget('key', 'key2', function(err, result) {
355
- console.log(result[0]);
356
- console.log(result[1]);
357
- // >> 'bar2'
358
- // >> 'bar3'
359
-
360
- // Delete from all caches
361
- multiCache.del('key', 'key2');
362
- // ...or with an Array
363
- multiCache.del(['key', 'key2']);
364
- });
365
- });
366
-
367
- // Note: options with ttl are optional in wrap()
368
- multiCache.wrap(key2, function (cb) {
369
- getUser(userId2, cb);
370
- }, {ttl: ttl}, function (err, user) {
371
- console.log(user);
372
-
373
- // Second time fetches user from memoryCache, since it's highest priority.
374
- // If the data expires in the memory cache, the next fetch would pull it from
375
- // the 'someOtherCache', and set the data in memory again.
376
- multiCache.wrap(key2, function (cb) {
377
- getUser(userId2, cb);
378
- }, function (err, user) {
379
- console.log(user);
380
- });
381
- });
382
-
383
- // Multiple keys
384
- multiCache.wrap('key1', 'key2', function (cb) {
385
- getManyUser(['key1', 'key2'], cb);
386
- }, {ttl: ttl}, function (err, users) {
387
- console.log(users[0]);
388
- console.log(users[1]);
389
- });
390
- ```
391
-
392
- ### Specifying What to Cache in `wrap` Function
393
-
394
- Both the `caching` and `multicaching` modules allow you to pass in a callback function named
395
- `isCacheableValue` which is called by the `wrap` function with every value returned from cache or from the wrapped function.
396
- This lets you specify which values should and should not be cached by `wrap`. If the function returns true, it will be
397
- stored in cache. By default the caches cache everything except `undefined`.
398
-
399
- NOTE: The `set` functions in `caching` and `multicaching` do *not* use `isCacheableValue`.
400
-
401
- For example, if you don't want to cache `false` and `null`, you can pass in a function like this:
402
-
403
- ```javascript
404
-
405
- var isCacheableValue = function(value) {
406
- return value !== null && value !== false && value !== undefined;
407
- };
408
-
409
- ```
410
-
411
- Then pass it to `caching` like this:
412
-
413
- ```javascript
414
-
415
- var memoryCache = cacheManager.caching({store: 'memory', isCacheableValue: isCacheableValue});
416
-
417
- ```
418
-
419
- And pass it to `multicaching` like this:
420
-
421
- ```javascript
422
-
423
- var multiCache = cacheManager.multiCaching([memoryCache, someOtherCache], {
424
- isCacheableValue: isCacheableValue
425
- });
426
-
427
- ```
428
-
429
- ### Refresh cache keys in background
430
-
431
- Both the `caching` and `multicaching` modules support a mechanism to refresh expiring cache keys in background when using `wrap` function.
432
- This is done by adding a `refreshThreshold` attribute while creating the caching store.
433
-
434
- If `refreshThreshold` is set and if the `ttl` method is available for the used store, after retrieving a value from cache TTL will be checked.
435
- If the remaining TTL is less than `refreshThreshold`, the system will spawn a background worker to update the value, following same rules as standard fetching. In the meantime, the system will return the old value until expiration.
436
-
437
- In case of multicaching, the store that will be used for refresh is the one where the key will be found first (highest priority). The value will then be set in all the stores.
438
-
439
- NOTES:
440
-
441
- * In case of multicaching, the store that will be checked for refresh is the one where the key will be found first (highest priority).
442
- * If the threshold is low and the worker function is slow, the key may expire and you may encounter a racing condition with updating values.
443
- * The background refresh mechanism currently does not support providing multiple keys to `wrap` function.
444
- * The caching store needs to provide the `ttl` method.
445
-
446
- For example, pass the refreshThreshold to `caching` like this:
447
-
448
- ```javascript
449
- var redisStore = require('cache-manager-ioredis');
450
-
451
- var redisCache = cacheManager.caching({store: redisStore, refreshThreshold: 3, isCacheableValue: isCacheableValue});
452
- ```
453
-
454
- When a value will be retrieved from Redis with a remaining TTL < 3sec, the value will be updated in background.
455
-
456
- ### Development environment
457
- You may disable real caching but still get all the callback functionality working by setting `none` store.
458
-
459
- ## Docs
460
-
461
- To generate JSDOC 3 documentation:
462
-
463
- make docs
464
-
465
- ## Tests
466
-
467
- To run tests, first run:
468
-
469
- npm install -d
470
-
471
- Run the tests and JShint:
472
-
473
- make
48
+ - [node-cache-manager-couchbase](https://github.com/davidepellegatta/node-cache-manager-couchbase)
474
49
 
50
+ - [node-cache-manager-sqlite](https://github.com/maxpert/node-cache-manager-sqlite)
475
51
 
476
52
  ## Contribute
477
53
 
478
- If you would like to contribute to the project, please fork it and send us a pull request. Please add tests
479
- for any new features or bug fixes. Also run `make` before submitting the pull request.
480
-
54
+ If you would like to contribute to the project, please fork it and send us a pull request. Please add tests
55
+ for any new features or bug fixes.
481
56
 
482
57
  ## License
483
58
 
484
- node-cache-manager is licensed under the MIT license.
59
+ node-cache-manager is licensed under the [MIT license](./LICENSE).
@@ -0,0 +1,33 @@
1
+ import { MemoryCache, MemoryConfig } from './stores';
2
+ export declare type Config = {
3
+ ttl?: Ttl;
4
+ isCacheable?: (val: unknown) => boolean;
5
+ };
6
+ export declare type Ttl = number;
7
+ export declare type Store = {
8
+ get<T>(key: string): Promise<T | undefined>;
9
+ set<T>(key: string, data: T, ttl?: Ttl): Promise<void>;
10
+ del(key: string): Promise<void>;
11
+ reset(): Promise<void>;
12
+ mset(args: [string, unknown][], ttl?: Ttl): Promise<void>;
13
+ mget(...args: string[]): Promise<unknown[]>;
14
+ mdel(...args: string[]): Promise<void>;
15
+ keys(pattern?: string): Promise<string[]>;
16
+ ttl(key: string): Promise<number>;
17
+ };
18
+ export declare type StoreConfig = Config;
19
+ export declare type FactoryConfig<T> = T & Config;
20
+ export declare type FactoryStore<S extends Store, T extends object = never> = (config?: FactoryConfig<T>) => S | Promise<S>;
21
+ export declare type Stores<S extends Store, T extends object> = 'memory' | Store | FactoryStore<S, T>;
22
+ export declare type CachingConfig<T> = MemoryConfig | StoreConfig | FactoryConfig<T>;
23
+ export declare type Cache<S extends Store = Store> = {
24
+ set: (key: string, value: unknown, ttl?: Ttl) => Promise<void>;
25
+ get: <T>(key: string) => Promise<T | undefined>;
26
+ del: (key: string) => Promise<void>;
27
+ reset: () => Promise<void>;
28
+ wrap<T>(key: string, fn: () => Promise<T>): Promise<T>;
29
+ store: S;
30
+ };
31
+ export declare function caching(name: 'memory', args?: MemoryConfig): Promise<MemoryCache>;
32
+ export declare function caching<S extends Store>(store: S): Promise<Cache<S>>;
33
+ export declare function caching<S extends Store, T extends object = never>(factory: FactoryStore<S, T>, args?: FactoryConfig<T>): Promise<Cache<S>>;
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ exports.__esModule = true;
39
+ exports.caching = void 0;
40
+ var stores_1 = require("./stores");
41
+ /**
42
+ * Generic caching interface that wraps any caching library with a compatible interface.
43
+ */
44
+ function caching(factory, args) {
45
+ return __awaiter(this, void 0, void 0, function () {
46
+ var store;
47
+ var _this = this;
48
+ return __generator(this, function (_a) {
49
+ switch (_a.label) {
50
+ case 0:
51
+ if (!(factory === 'memory')) return [3 /*break*/, 1];
52
+ store = (0, stores_1.memoryStore)(args);
53
+ return [3 /*break*/, 4];
54
+ case 1:
55
+ if (!(typeof factory === 'function')) return [3 /*break*/, 3];
56
+ return [4 /*yield*/, factory(args)];
57
+ case 2:
58
+ store = _a.sent();
59
+ return [3 /*break*/, 4];
60
+ case 3:
61
+ store = factory;
62
+ _a.label = 4;
63
+ case 4: return [2 /*return*/, {
64
+ /**
65
+ * Wraps a function in cache. I.e., the first time the function is run,
66
+ * its results are stored in cache so subsequent calls retrieve from cache
67
+ * instead of calling the function.
68
+
69
+ * @example
70
+ * const result = await cache.wrap('key', () => Promise.resolve(1));
71
+ *
72
+ */
73
+ wrap: function (key, fn) { return __awaiter(_this, void 0, void 0, function () {
74
+ var value, result;
75
+ return __generator(this, function (_a) {
76
+ switch (_a.label) {
77
+ case 0: return [4 /*yield*/, store.get(key)];
78
+ case 1:
79
+ value = _a.sent();
80
+ if (!(value === undefined)) return [3 /*break*/, 4];
81
+ return [4 /*yield*/, fn()];
82
+ case 2:
83
+ result = _a.sent();
84
+ return [4 /*yield*/, store.set(key, result)];
85
+ case 3:
86
+ _a.sent();
87
+ return [2 /*return*/, result];
88
+ case 4: return [2 /*return*/, value];
89
+ }
90
+ });
91
+ }); },
92
+ store: store,
93
+ del: function (key) { return store.del(key); },
94
+ get: function (key) { return store.get(key); },
95
+ set: function (key, value, ttl) { return store.set(key, value, ttl); },
96
+ reset: function () { return store.reset(); }
97
+ }];
98
+ }
99
+ });
100
+ });
101
+ }
102
+ exports.caching = caching;
103
+ //# sourceMappingURL=caching.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"caching.js","sourceRoot":"","sources":["../src/caching.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mCAAkE;AAqDlE;;GAEG;AACH,SAAsB,OAAO,CAC3B,OAAqB,EACrB,IAAuB;;;;;;;yBAGnB,CAAA,OAAO,KAAK,QAAQ,CAAA,EAApB,wBAAoB;oBAAE,KAAK,GAAG,IAAA,oBAAW,EAAC,IAAoB,CAAC,CAAC;;;yBAC3D,CAAA,OAAO,OAAO,KAAK,UAAU,CAAA,EAA7B,wBAA6B;oBAC5B,qBAAM,OAAO,CAAC,IAAwB,CAAC,EAAA;;oBAA/C,KAAK,GAAG,SAAuC,CAAC;;;oBAC7C,KAAK,GAAG,OAAO,CAAC;;wBAErB,sBAAO;wBACL;;;;;;;;2BAQG;wBACH,IAAI,EAAE,UAAU,GAAW,EAAE,EAAoB;;;;4CACjC,qBAAM,KAAK,CAAC,GAAG,CAAI,GAAG,CAAC,EAAA;;wCAA/B,KAAK,GAAG,SAAuB;6CACjC,CAAA,KAAK,KAAK,SAAS,CAAA,EAAnB,wBAAmB;wCACN,qBAAM,EAAE,EAAE,EAAA;;wCAAnB,MAAM,GAAG,SAAU;wCACzB,qBAAM,KAAK,CAAC,GAAG,CAAI,GAAG,EAAE,MAAM,CAAC,EAAA;;wCAA/B,SAA+B,CAAC;wCAChC,sBAAO,MAAM,EAAC;4CAEhB,sBAAO,KAAK,EAAC;;;6BACd;wBACD,KAAK,EAAE,KAAU;wBACjB,GAAG,EAAE,UAAC,GAAW,IAAK,OAAA,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAd,CAAc;wBACpC,GAAG,EAAE,UAAI,GAAW,IAAK,OAAA,KAAK,CAAC,GAAG,CAAI,GAAG,CAAC,EAAjB,CAAiB;wBAC1C,GAAG,EAAE,UAAC,GAAW,EAAE,KAAc,EAAE,GAAS,IAAK,OAAA,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,CAAC,EAA1B,CAA0B;wBAC3E,KAAK,EAAE,cAAM,OAAA,KAAK,CAAC,KAAK,EAAE,EAAb,CAAa;qBAC3B,EAAC;;;;CACH;AAnCD,0BAmCC"}
@@ -0,0 +1,3 @@
1
+ export * from './caching';
2
+ export * from './multi-caching';
3
+ export * from './stores';
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ exports.__esModule = true;
17
+ __exportStar(require("./caching"), exports);
18
+ __exportStar(require("./multi-caching"), exports);
19
+ __exportStar(require("./stores"), exports);
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,kDAAgC;AAChC,2CAAyB"}