cache-manager 6.3.2 → 6.4.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/README.md CHANGED
@@ -39,11 +39,16 @@ If you are looking for older documentation you can find it here:
39
39
  * [.mdel](#mdel)
40
40
  * [.clear](#clear)
41
41
  * [.wrap](#wrap)
42
+ * [.disconnect](#disconnect)
42
43
  * [Events](#events)
43
44
  * [.set](#set)
44
45
  * [.del](#del)
45
46
  * [.clear](#clear)
46
47
  * [.refresh](#refresh)
48
+ * [Properties](#properties)
49
+ * [.cacheId](#cacheId)
50
+ * [.stores](#stores)
51
+ * [Doing Iteration on Stores](#doing-iteration-on-stores)
47
52
  * [Update on `redis` and `ioredis` Support](#update-on-redis-and-ioredis-support)
48
53
  * [Using Legacy Storage Adapters](#using-legacy-storage-adapters)
49
54
  * [Contribute](#contribute)
@@ -165,7 +170,7 @@ const cache = createCache({ stores: [keyv] });
165
170
  - **ttl**?: number - Default time to live in milliseconds.
166
171
 
167
172
  The time to live in milliseconds. This is the maximum amount of time that an item can be in the cache before it is removed.
168
- - **refreshThreshold**?: number - Default refreshThreshold in milliseconds.
173
+ - **refreshThreshold**?: number | (value:T) => number - Default refreshThreshold in milliseconds. You can also provide a function that will return the refreshThreshold based on the value.
169
174
 
170
175
  If the remaining TTL is less than **refreshThreshold**, the system will update the value asynchronously in background.
171
176
  - **refreshAllStores**?: boolean - Default false
@@ -181,6 +186,10 @@ const cache = createCache({ stores: [keyv] });
181
186
  * `clear` - will not wait for all stores to finish.
182
187
  * `wrap` - will do the same as `get` and `set` (return the first value found and not wait for all stores to finish).
183
188
 
189
+ - **cacheId**?: string - Defaults to random string
190
+
191
+ Unique identifier for the cache instance. This is primarily used to not have conflicts when using `wrap` with multiple cache instances.
192
+
184
193
  # Methods
185
194
  ## set
186
195
  `set(key, value, [ttl]): Promise<value>`
@@ -315,7 +324,7 @@ See unit tests in [`test/clear.test.ts`](./test/clear.test.ts) for more informat
315
324
 
316
325
  Wraps a function in cache. The first time the function is run, its results are stored in cache so subsequent calls retrieve from cache instead of calling the function.
317
326
 
318
- If `refreshThreshold` is set and the remaining TTL is less than `refreshThreshold`, the system will update the value asynchronously. In the meantime, the system will return the old value until expiration.
327
+ If `refreshThreshold` is set and the remaining TTL is less than `refreshThreshold`, the system will update the value asynchronously. In the meantime, the system will return the old value until expiration. You can also provide a function that will return the refreshThreshold based on the value `(value:T) => number`.
319
328
 
320
329
  ```typescript
321
330
  await cache.wrap('key', () => 1, 5000, 3000)
@@ -337,6 +346,10 @@ await cache.wrap('key', () => 3, 5000, 3000)
337
346
  // return data from cache, function will not be called
338
347
  // => 2
339
348
 
349
+ await cache.wrap('key', () => 4, 5000, () => 3000);
350
+ // return data from cache, function will not be called
351
+ // => 4
352
+
340
353
  await cache.wrap('error', () => {
341
354
  throw new Error('failed')
342
355
  })
@@ -352,9 +365,9 @@ See unit tests in [`test/wrap.test.ts`](./test/wrap.test.ts) for more informatio
352
365
 
353
366
  ## disconnect
354
367
 
355
- `disconnect(key): Promise<void>`
368
+ `disconnect(): Promise<void>`
356
369
 
357
- Will disconnect from the relevant store(s). It is highly recomended to use this when using a [Keyv](https://keyv.org/) storage adapter that requires a disconnect. For each storage adapter, the use case for when to use disconnect is different. An example is that `@keyv/redis` should be used only when you are done with the cache.
370
+ Will disconnect from the relevant store(s). It is highly recommended to use this when using a [Keyv](https://keyv.org/) storage adapter that requires a disconnect. For each storage adapter, the use case for when to use disconnect is different. An example is that `@keyv/redis` should be used only when you are done with the cache.
358
371
 
359
372
  ```ts
360
373
  await cache.disconnect();
@@ -362,6 +375,24 @@ await cache.disconnect();
362
375
 
363
376
  See unit tests in [`test/disconnect.test.ts`](./test/disconnect.test.ts) for more information.
364
377
 
378
+ # Properties
379
+
380
+ ## cacheId
381
+ `cacheId(): string`
382
+
383
+ Returns cache instance id. This is primarily used to not have conflicts when using `wrap` with multiple cache instances.
384
+
385
+ ## stores
386
+ `stores(): Keyv[]`
387
+
388
+ Returns the list of Keyv instances. This can be used to get the list of stores and then use the Keyv API to interact with the store directly.
389
+
390
+ ```ts
391
+ const cache = createCache({cacheId: 'my-cache-id'});
392
+ cache.cacheId(); // => 'my-cache-id'
393
+ ```
394
+ See unit tests in [`test/cache-id.test.ts`](./test/get.test.ts) for more information.
395
+
365
396
  # Events
366
397
  ## set
367
398
  Fired when a key has been added or changed.
@@ -405,6 +436,38 @@ cache.on('refresh', ({ key, value, error }) => {
405
436
 
406
437
  See unit tests in [`test/events.test.ts`](./test/events.test.ts) for more information.
407
438
 
439
+ # Doing Iteration on Stores
440
+
441
+ You can use the `stores` method to get the list of stores and then use the Keyv API to interact with the store directly. Below is an example of iterating over all stores and getting all keys:
442
+
443
+ ```ts
444
+ import Keyv from 'keyv';
445
+ import { createKeyv } from '@keyv/redis';
446
+ import { createCache } from 'cache-manager';
447
+
448
+ const keyv = new Keyv();
449
+ const keyvRedis = createKeyv('redis://user:pass@localhost:6379');
450
+
451
+ const cache = createCache({
452
+ stores: [keyv, keyvRedis],
453
+ });
454
+
455
+ // add some data
456
+ await cache.set('key-1', 'value 1');
457
+ await cache.set('key-2', 'value 2');
458
+
459
+ // get the store you want to iterate over. In this example we are using the second store (redis)
460
+ const store = cache.stores[1];
461
+
462
+ if(store?.iterator) {
463
+ for await (const [key, value] of store.iterator({})) {
464
+ console.log(key, value);
465
+ }
466
+ }
467
+ ```
468
+
469
+ WARNING: Be careful when using `iterator` as it can cause major performance issues with the amount of data being retrieved. Also, Not all storage adapters support `iterator` so you may need to check the documentation for the storage adapter you are using.
470
+
408
471
  # Update on redis and ioredis Support
409
472
 
410
473
  We will not be supporting `cache-manager-ioredis-yet` or `cache-manager-redis-yet` in the future as we have moved to using `Keyv` as the storage adapter `@keyv/redis`.
package/dist/index.cjs CHANGED
@@ -156,6 +156,7 @@ var createCache = (options) => {
156
156
  const eventEmitter = new import_node_events.default();
157
157
  const stores = options?.stores?.length ? options.stores : [new import_keyv.Keyv()];
158
158
  const nonBlocking = options?.nonBlocking ?? false;
159
+ const _cacheId = options?.cacheId ?? Math.random().toString(36).slice(2);
159
160
  const get = async (key) => {
160
161
  let result = null;
161
162
  if (nonBlocking) {
@@ -305,10 +306,11 @@ var createCache = (options) => {
305
306
  return Promise.reject(error);
306
307
  }
307
308
  };
308
- const wrap = async (key, fnc, ttl2, refreshThreshold) => coalesceAsync(key, async () => {
309
+ const wrap = async (key, fnc, ttl2, refreshThreshold) => coalesceAsync(`${_cacheId}::${key}`, async () => {
309
310
  let value;
310
311
  let i = 0;
311
312
  let remainingTtl;
313
+ const resolveTtl = (result) => runIfFn(ttl2, result) ?? options?.ttl;
312
314
  for (; i < stores.length; i++) {
313
315
  try {
314
316
  const data = await stores[i].get(key, { raw: true });
@@ -324,15 +326,14 @@ var createCache = (options) => {
324
326
  }
325
327
  if (value === void 0) {
326
328
  const result = await fnc();
327
- await set(stores, key, result, runIfFn(ttl2, result) ?? options?.ttl);
329
+ await set(stores, key, result, resolveTtl(result));
328
330
  return result;
329
331
  }
330
- const ms = runIfFn(ttl2, value) ?? options?.ttl;
331
- const shouldRefresh = lt(remainingTtl, refreshThreshold ?? options?.refreshThreshold);
332
+ const shouldRefresh = lt(remainingTtl, runIfFn(refreshThreshold, value) ?? options?.refreshThreshold);
332
333
  if (shouldRefresh) {
333
- coalesceAsync(`+++${key}`, fnc).then(async (result) => {
334
+ coalesceAsync(`+++${_cacheId}__${key}`, fnc).then(async (result) => {
334
335
  try {
335
- await set(options?.refreshAllStores ? stores : stores.slice(0, i + 1), key, result, ms);
336
+ await set(options?.refreshAllStores ? stores : stores.slice(0, i + 1), key, result, resolveTtl(result));
336
337
  eventEmitter.emit("refresh", { key, value: result });
337
338
  } catch (error) {
338
339
  eventEmitter.emit("refresh", { key, value, error });
@@ -342,7 +343,7 @@ var createCache = (options) => {
342
343
  });
343
344
  }
344
345
  if (!shouldRefresh && i > 0) {
345
- await set(stores.slice(0, i), key, value, ms);
346
+ await set(stores.slice(0, i), key, value, resolveTtl(value));
346
347
  }
347
348
  return value;
348
349
  });
@@ -355,6 +356,7 @@ var createCache = (options) => {
355
356
  return Promise.reject(error);
356
357
  }
357
358
  };
359
+ const cacheId = () => _cacheId;
358
360
  return {
359
361
  get,
360
362
  mget,
@@ -367,7 +369,9 @@ var createCache = (options) => {
367
369
  wrap,
368
370
  on,
369
371
  off,
370
- disconnect
372
+ disconnect,
373
+ cacheId,
374
+ stores
371
375
  };
372
376
  };
373
377
  // Annotate the CommonJS export names for ESM import in node:
package/dist/index.d.cts CHANGED
@@ -38,6 +38,7 @@ type CreateCacheOptions = {
38
38
  refreshThreshold?: number;
39
39
  refreshAllStores?: boolean;
40
40
  nonBlocking?: boolean;
41
+ cacheId?: string;
41
42
  };
42
43
  type Cache = {
43
44
  get: <T>(key: string) => Promise<T | null>;
@@ -56,10 +57,12 @@ type Cache = {
56
57
  del: (key: string) => Promise<boolean>;
57
58
  mdel: (keys: string[]) => Promise<boolean>;
58
59
  clear: () => Promise<boolean>;
59
- wrap: <T>(key: string, fnc: () => T | Promise<T>, ttl?: number | ((value: T) => number), refreshThreshold?: number) => Promise<T>;
60
+ wrap: <T>(key: string, fnc: () => T | Promise<T>, ttl?: number | ((value: T) => number), refreshThreshold?: number | ((value: T) => number)) => Promise<T>;
60
61
  on: <E extends keyof Events>(event: E, listener: Events[E]) => EventEmitter;
61
62
  off: <E extends keyof Events>(event: E, listener: Events[E]) => EventEmitter;
62
63
  disconnect: () => Promise<undefined>;
64
+ cacheId: () => string;
65
+ stores: Keyv[];
63
66
  };
64
67
  type Events = {
65
68
  set: <T>(data: {
package/dist/index.d.ts CHANGED
@@ -38,6 +38,7 @@ type CreateCacheOptions = {
38
38
  refreshThreshold?: number;
39
39
  refreshAllStores?: boolean;
40
40
  nonBlocking?: boolean;
41
+ cacheId?: string;
41
42
  };
42
43
  type Cache = {
43
44
  get: <T>(key: string) => Promise<T | null>;
@@ -56,10 +57,12 @@ type Cache = {
56
57
  del: (key: string) => Promise<boolean>;
57
58
  mdel: (keys: string[]) => Promise<boolean>;
58
59
  clear: () => Promise<boolean>;
59
- wrap: <T>(key: string, fnc: () => T | Promise<T>, ttl?: number | ((value: T) => number), refreshThreshold?: number) => Promise<T>;
60
+ wrap: <T>(key: string, fnc: () => T | Promise<T>, ttl?: number | ((value: T) => number), refreshThreshold?: number | ((value: T) => number)) => Promise<T>;
60
61
  on: <E extends keyof Events>(event: E, listener: Events[E]) => EventEmitter;
61
62
  off: <E extends keyof Events>(event: E, listener: Events[E]) => EventEmitter;
62
63
  disconnect: () => Promise<undefined>;
64
+ cacheId: () => string;
65
+ stores: Keyv[];
63
66
  };
64
67
  type Events = {
65
68
  set: <T>(data: {
package/dist/index.js CHANGED
@@ -121,6 +121,7 @@ var createCache = (options) => {
121
121
  const eventEmitter = new EventEmitter();
122
122
  const stores = options?.stores?.length ? options.stores : [new Keyv()];
123
123
  const nonBlocking = options?.nonBlocking ?? false;
124
+ const _cacheId = options?.cacheId ?? Math.random().toString(36).slice(2);
124
125
  const get = async (key) => {
125
126
  let result = null;
126
127
  if (nonBlocking) {
@@ -270,10 +271,11 @@ var createCache = (options) => {
270
271
  return Promise.reject(error);
271
272
  }
272
273
  };
273
- const wrap = async (key, fnc, ttl2, refreshThreshold) => coalesceAsync(key, async () => {
274
+ const wrap = async (key, fnc, ttl2, refreshThreshold) => coalesceAsync(`${_cacheId}::${key}`, async () => {
274
275
  let value;
275
276
  let i = 0;
276
277
  let remainingTtl;
278
+ const resolveTtl = (result) => runIfFn(ttl2, result) ?? options?.ttl;
277
279
  for (; i < stores.length; i++) {
278
280
  try {
279
281
  const data = await stores[i].get(key, { raw: true });
@@ -289,15 +291,14 @@ var createCache = (options) => {
289
291
  }
290
292
  if (value === void 0) {
291
293
  const result = await fnc();
292
- await set(stores, key, result, runIfFn(ttl2, result) ?? options?.ttl);
294
+ await set(stores, key, result, resolveTtl(result));
293
295
  return result;
294
296
  }
295
- const ms = runIfFn(ttl2, value) ?? options?.ttl;
296
- const shouldRefresh = lt(remainingTtl, refreshThreshold ?? options?.refreshThreshold);
297
+ const shouldRefresh = lt(remainingTtl, runIfFn(refreshThreshold, value) ?? options?.refreshThreshold);
297
298
  if (shouldRefresh) {
298
- coalesceAsync(`+++${key}`, fnc).then(async (result) => {
299
+ coalesceAsync(`+++${_cacheId}__${key}`, fnc).then(async (result) => {
299
300
  try {
300
- await set(options?.refreshAllStores ? stores : stores.slice(0, i + 1), key, result, ms);
301
+ await set(options?.refreshAllStores ? stores : stores.slice(0, i + 1), key, result, resolveTtl(result));
301
302
  eventEmitter.emit("refresh", { key, value: result });
302
303
  } catch (error) {
303
304
  eventEmitter.emit("refresh", { key, value, error });
@@ -307,7 +308,7 @@ var createCache = (options) => {
307
308
  });
308
309
  }
309
310
  if (!shouldRefresh && i > 0) {
310
- await set(stores.slice(0, i), key, value, ms);
311
+ await set(stores.slice(0, i), key, value, resolveTtl(value));
311
312
  }
312
313
  return value;
313
314
  });
@@ -320,6 +321,7 @@ var createCache = (options) => {
320
321
  return Promise.reject(error);
321
322
  }
322
323
  };
324
+ const cacheId = () => _cacheId;
323
325
  return {
324
326
  get,
325
327
  mget,
@@ -332,7 +334,9 @@ var createCache = (options) => {
332
334
  wrap,
333
335
  on,
334
336
  off,
335
- disconnect
337
+ disconnect,
338
+ cacheId,
339
+ stores
336
340
  };
337
341
  };
338
342
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cache-manager",
3
- "version": "6.3.2",
3
+ "version": "6.4.0",
4
4
  "description": "Cache Manager for Node.js",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -53,17 +53,17 @@
53
53
  "keyv": "^5.2.3"
54
54
  },
55
55
  "devDependencies": {
56
- "@faker-js/faker": "^9.3.0",
56
+ "@faker-js/faker": "^9.4.0",
57
57
  "@keyv/redis": "^4.2.0",
58
- "@types/node": "^22.10.2",
59
- "@vitest/coverage-v8": "^2.1.8",
58
+ "@types/node": "^22.10.9",
59
+ "@vitest/coverage-v8": "^3.0.4",
60
60
  "cache-manager-redis-yet": "^5.1.5",
61
61
  "rimraf": "^6.0.1",
62
62
  "tsup": "^8.3.5",
63
- "typescript": "^5.7.2",
64
- "vitest": "^2.1.8",
63
+ "typescript": "^5.7.3",
64
+ "vitest": "^3.0.4",
65
65
  "xo": "^0.60.0",
66
- "cacheable": "^1.8.6"
66
+ "cacheable": "^1.8.8"
67
67
  },
68
68
  "xo": {
69
69
  "rules": {