cache-manager 6.3.2 → 6.4.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
@@ -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>`
@@ -313,9 +322,15 @@ See unit tests in [`test/clear.test.ts`](./test/clear.test.ts) for more informat
313
322
  ## wrap
314
323
  `wrap(key, fn: async () => value, [ttl], [refreshThreshold]): Promise<value>`
315
324
 
325
+ Alternatively, with optional parameters as options object supporting a `raw` parameter:
326
+
327
+ `wrap(key, fn: async () => value, { ttl?: number, refreshThreshold?: number, raw?: true }): Promise<value>`
328
+
316
329
  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
330
 
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.
331
+ 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`.
332
+
333
+ If the object format for the optional parameters is used, an additional `raw` parameter can be applied, changing the function return type to raw data including expiration timestamp as `{ value: [data], expires: [timestamp] }`.
319
334
 
320
335
  ```typescript
321
336
  await cache.wrap('key', () => 1, 5000, 3000)
@@ -326,6 +341,10 @@ await cache.wrap('key', () => 2, 5000, 3000)
326
341
  // return data from cache, function will not be called again
327
342
  // => 1
328
343
 
344
+ await cache.wrap('key', () => 2, { ttl: 5000, refreshThreshold: 3000, raw: true })
345
+ // returns raw data including expiration timestamp
346
+ // => { value: 1, expires: [timestamp] }
347
+
329
348
  // wait 3 seconds
330
349
  await sleep(3000)
331
350
 
@@ -337,6 +356,10 @@ await cache.wrap('key', () => 3, 5000, 3000)
337
356
  // return data from cache, function will not be called
338
357
  // => 2
339
358
 
359
+ await cache.wrap('key', () => 4, 5000, () => 3000);
360
+ // return data from cache, function will not be called
361
+ // => 4
362
+
340
363
  await cache.wrap('error', () => {
341
364
  throw new Error('failed')
342
365
  })
@@ -352,9 +375,9 @@ See unit tests in [`test/wrap.test.ts`](./test/wrap.test.ts) for more informatio
352
375
 
353
376
  ## disconnect
354
377
 
355
- `disconnect(key): Promise<void>`
378
+ `disconnect(): Promise<void>`
356
379
 
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.
380
+ 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
381
 
359
382
  ```ts
360
383
  await cache.disconnect();
@@ -362,6 +385,24 @@ await cache.disconnect();
362
385
 
363
386
  See unit tests in [`test/disconnect.test.ts`](./test/disconnect.test.ts) for more information.
364
387
 
388
+ # Properties
389
+
390
+ ## cacheId
391
+ `cacheId(): string`
392
+
393
+ Returns cache instance id. This is primarily used to not have conflicts when using `wrap` with multiple cache instances.
394
+
395
+ ## stores
396
+ `stores(): Keyv[]`
397
+
398
+ 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.
399
+
400
+ ```ts
401
+ const cache = createCache({cacheId: 'my-cache-id'});
402
+ cache.cacheId(); // => 'my-cache-id'
403
+ ```
404
+ See unit tests in [`test/cache-id.test.ts`](./test/get.test.ts) for more information.
405
+
365
406
  # Events
366
407
  ## set
367
408
  Fired when a key has been added or changed.
@@ -405,6 +446,38 @@ cache.on('refresh', ({ key, value, error }) => {
405
446
 
406
447
  See unit tests in [`test/events.test.ts`](./test/events.test.ts) for more information.
407
448
 
449
+ # Doing Iteration on Stores
450
+
451
+ 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:
452
+
453
+ ```ts
454
+ import Keyv from 'keyv';
455
+ import { createKeyv } from '@keyv/redis';
456
+ import { createCache } from 'cache-manager';
457
+
458
+ const keyv = new Keyv();
459
+ const keyvRedis = createKeyv('redis://user:pass@localhost:6379');
460
+
461
+ const cache = createCache({
462
+ stores: [keyv, keyvRedis],
463
+ });
464
+
465
+ // add some data
466
+ await cache.set('key-1', 'value 1');
467
+ await cache.set('key-2', 'value 2');
468
+
469
+ // get the store you want to iterate over. In this example we are using the second store (redis)
470
+ const store = cache.stores[1];
471
+
472
+ if(store?.iterator) {
473
+ for await (const [key, value] of store.iterator({})) {
474
+ console.log(key, value);
475
+ }
476
+ }
477
+ ```
478
+
479
+ 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.
480
+
408
481
  # Update on redis and ioredis Support
409
482
 
410
483
  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
@@ -92,6 +92,11 @@ async function coalesceAsync(key, fnc) {
92
92
  return enqueue(key);
93
93
  }
94
94
 
95
+ // src/is-object.ts
96
+ function isObject(value) {
97
+ return value !== null && typeof value === "object" && !Array.isArray(value);
98
+ }
99
+
95
100
  // src/run-if-fn.ts
96
101
  function runIfFn(valueOrFunction, ...arguments_) {
97
102
  return typeof valueOrFunction === "function" ? valueOrFunction(...arguments_) : valueOrFunction;
@@ -156,6 +161,7 @@ var createCache = (options) => {
156
161
  const eventEmitter = new import_node_events.default();
157
162
  const stores = options?.stores?.length ? options.stores : [new import_keyv.Keyv()];
158
163
  const nonBlocking = options?.nonBlocking ?? false;
164
+ const _cacheId = options?.cacheId ?? Math.random().toString(36).slice(2);
159
165
  const get = async (key) => {
160
166
  let result = null;
161
167
  if (nonBlocking) {
@@ -305,15 +311,19 @@ var createCache = (options) => {
305
311
  return Promise.reject(error);
306
312
  }
307
313
  };
308
- const wrap = async (key, fnc, ttl2, refreshThreshold) => coalesceAsync(key, async () => {
314
+ const wrap = async (key, fnc, ttlOrOptions, refreshThresholdParameter) => coalesceAsync(`${_cacheId}::${key}`, async () => {
309
315
  let value;
316
+ let rawData;
310
317
  let i = 0;
311
318
  let remainingTtl;
319
+ const { ttl: ttl2, refreshThreshold, raw } = isObject(ttlOrOptions) ? ttlOrOptions : { ttl: ttlOrOptions, refreshThreshold: refreshThresholdParameter };
320
+ const resolveTtl = (result) => runIfFn(ttl2, result) ?? options?.ttl;
312
321
  for (; i < stores.length; i++) {
313
322
  try {
314
323
  const data = await stores[i].get(key, { raw: true });
315
324
  if (data !== void 0) {
316
325
  value = data.value;
326
+ rawData = data;
317
327
  if (typeof data.expires === "number") {
318
328
  remainingTtl = Math.max(0, data.expires - Date.now());
319
329
  }
@@ -324,15 +334,15 @@ var createCache = (options) => {
324
334
  }
325
335
  if (value === void 0) {
326
336
  const result = await fnc();
327
- await set(stores, key, result, runIfFn(ttl2, result) ?? options?.ttl);
328
- return result;
337
+ const ttl3 = resolveTtl(result);
338
+ await set(stores, key, result, ttl3);
339
+ return raw ? { value: result, expires: Date.now() + ttl3 } : result;
329
340
  }
330
- const ms = runIfFn(ttl2, value) ?? options?.ttl;
331
- const shouldRefresh = lt(remainingTtl, refreshThreshold ?? options?.refreshThreshold);
341
+ const shouldRefresh = lt(remainingTtl, runIfFn(refreshThreshold, value) ?? options?.refreshThreshold);
332
342
  if (shouldRefresh) {
333
- coalesceAsync(`+++${key}`, fnc).then(async (result) => {
343
+ coalesceAsync(`+++${_cacheId}__${key}`, fnc).then(async (result) => {
334
344
  try {
335
- await set(options?.refreshAllStores ? stores : stores.slice(0, i + 1), key, result, ms);
345
+ await set(options?.refreshAllStores ? stores : stores.slice(0, i + 1), key, result, resolveTtl(result));
336
346
  eventEmitter.emit("refresh", { key, value: result });
337
347
  } catch (error) {
338
348
  eventEmitter.emit("refresh", { key, value, error });
@@ -342,9 +352,9 @@ var createCache = (options) => {
342
352
  });
343
353
  }
344
354
  if (!shouldRefresh && i > 0) {
345
- await set(stores.slice(0, i), key, value, ms);
355
+ await set(stores.slice(0, i), key, value, resolveTtl(value));
346
356
  }
347
- return value;
357
+ return raw ? rawData : value;
348
358
  });
349
359
  const on = (event, listener) => eventEmitter.addListener(event, listener);
350
360
  const off = (event, listener) => eventEmitter.removeListener(event, listener);
@@ -355,6 +365,7 @@ var createCache = (options) => {
355
365
  return Promise.reject(error);
356
366
  }
357
367
  };
368
+ const cacheId = () => _cacheId;
358
369
  return {
359
370
  get,
360
371
  mget,
@@ -367,7 +378,9 @@ var createCache = (options) => {
367
378
  wrap,
368
379
  on,
369
380
  off,
370
- disconnect
381
+ disconnect,
382
+ cacheId,
383
+ stores
371
384
  };
372
385
  };
373
386
  // Annotate the CommonJS export names for ESM import in node:
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import EventEmitter from 'node:events';
2
- import { KeyvStoreAdapter, StoredData, Keyv } from 'keyv';
2
+ import { KeyvStoreAdapter, StoredData, Keyv, StoredDataRaw } from 'keyv';
3
3
 
4
4
  type CacheManagerStore = {
5
5
  name: string;
@@ -38,10 +38,18 @@ type CreateCacheOptions = {
38
38
  refreshThreshold?: number;
39
39
  refreshAllStores?: boolean;
40
40
  nonBlocking?: boolean;
41
+ cacheId?: string;
42
+ };
43
+ type WrapOptions<T> = {
44
+ ttl?: number | ((value: T) => number);
45
+ refreshThreshold?: number | ((value: T) => number);
46
+ };
47
+ type WrapOptionsRaw<T> = WrapOptions<T> & {
48
+ raw: true;
41
49
  };
42
50
  type Cache = {
43
51
  get: <T>(key: string) => Promise<T | null>;
44
- mget: <T>(keys: string[]) => Promise<[T]>;
52
+ mget: <T>(keys: string[]) => Promise<Array<T | null>>;
45
53
  ttl: (key: string) => Promise<number | null>;
46
54
  set: <T>(key: string, value: T, ttl?: number) => Promise<T>;
47
55
  mset: <T>(list: Array<{
@@ -56,10 +64,14 @@ type Cache = {
56
64
  del: (key: string) => Promise<boolean>;
57
65
  mdel: (keys: string[]) => Promise<boolean>;
58
66
  clear: () => Promise<boolean>;
59
- wrap: <T>(key: string, fnc: () => T | Promise<T>, ttl?: number | ((value: T) => number), refreshThreshold?: number) => Promise<T>;
60
67
  on: <E extends keyof Events>(event: E, listener: Events[E]) => EventEmitter;
61
68
  off: <E extends keyof Events>(event: E, listener: Events[E]) => EventEmitter;
62
69
  disconnect: () => Promise<undefined>;
70
+ cacheId: () => string;
71
+ stores: Keyv[];
72
+ wrap<T>(key: string, fnc: () => T | Promise<T>, ttl?: number | ((value: T) => number), refreshThreshold?: number | ((value: T) => number)): Promise<T>;
73
+ wrap<T>(key: string, fnc: () => T | Promise<T>, options: WrapOptions<T>): Promise<T>;
74
+ wrap<T>(key: string, fnc: () => T | Promise<T>, options: WrapOptionsRaw<T>): Promise<StoredDataRaw<T>>;
63
75
  };
64
76
  type Events = {
65
77
  set: <T>(data: {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import EventEmitter from 'node:events';
2
- import { KeyvStoreAdapter, StoredData, Keyv } from 'keyv';
2
+ import { KeyvStoreAdapter, StoredData, Keyv, StoredDataRaw } from 'keyv';
3
3
 
4
4
  type CacheManagerStore = {
5
5
  name: string;
@@ -38,10 +38,18 @@ type CreateCacheOptions = {
38
38
  refreshThreshold?: number;
39
39
  refreshAllStores?: boolean;
40
40
  nonBlocking?: boolean;
41
+ cacheId?: string;
42
+ };
43
+ type WrapOptions<T> = {
44
+ ttl?: number | ((value: T) => number);
45
+ refreshThreshold?: number | ((value: T) => number);
46
+ };
47
+ type WrapOptionsRaw<T> = WrapOptions<T> & {
48
+ raw: true;
41
49
  };
42
50
  type Cache = {
43
51
  get: <T>(key: string) => Promise<T | null>;
44
- mget: <T>(keys: string[]) => Promise<[T]>;
52
+ mget: <T>(keys: string[]) => Promise<Array<T | null>>;
45
53
  ttl: (key: string) => Promise<number | null>;
46
54
  set: <T>(key: string, value: T, ttl?: number) => Promise<T>;
47
55
  mset: <T>(list: Array<{
@@ -56,10 +64,14 @@ type Cache = {
56
64
  del: (key: string) => Promise<boolean>;
57
65
  mdel: (keys: string[]) => Promise<boolean>;
58
66
  clear: () => Promise<boolean>;
59
- wrap: <T>(key: string, fnc: () => T | Promise<T>, ttl?: number | ((value: T) => number), refreshThreshold?: number) => Promise<T>;
60
67
  on: <E extends keyof Events>(event: E, listener: Events[E]) => EventEmitter;
61
68
  off: <E extends keyof Events>(event: E, listener: Events[E]) => EventEmitter;
62
69
  disconnect: () => Promise<undefined>;
70
+ cacheId: () => string;
71
+ stores: Keyv[];
72
+ wrap<T>(key: string, fnc: () => T | Promise<T>, ttl?: number | ((value: T) => number), refreshThreshold?: number | ((value: T) => number)): Promise<T>;
73
+ wrap<T>(key: string, fnc: () => T | Promise<T>, options: WrapOptions<T>): Promise<T>;
74
+ wrap<T>(key: string, fnc: () => T | Promise<T>, options: WrapOptionsRaw<T>): Promise<StoredDataRaw<T>>;
63
75
  };
64
76
  type Events = {
65
77
  set: <T>(data: {
package/dist/index.js CHANGED
@@ -57,6 +57,11 @@ async function coalesceAsync(key, fnc) {
57
57
  return enqueue(key);
58
58
  }
59
59
 
60
+ // src/is-object.ts
61
+ function isObject(value) {
62
+ return value !== null && typeof value === "object" && !Array.isArray(value);
63
+ }
64
+
60
65
  // src/run-if-fn.ts
61
66
  function runIfFn(valueOrFunction, ...arguments_) {
62
67
  return typeof valueOrFunction === "function" ? valueOrFunction(...arguments_) : valueOrFunction;
@@ -121,6 +126,7 @@ var createCache = (options) => {
121
126
  const eventEmitter = new EventEmitter();
122
127
  const stores = options?.stores?.length ? options.stores : [new Keyv()];
123
128
  const nonBlocking = options?.nonBlocking ?? false;
129
+ const _cacheId = options?.cacheId ?? Math.random().toString(36).slice(2);
124
130
  const get = async (key) => {
125
131
  let result = null;
126
132
  if (nonBlocking) {
@@ -270,15 +276,19 @@ var createCache = (options) => {
270
276
  return Promise.reject(error);
271
277
  }
272
278
  };
273
- const wrap = async (key, fnc, ttl2, refreshThreshold) => coalesceAsync(key, async () => {
279
+ const wrap = async (key, fnc, ttlOrOptions, refreshThresholdParameter) => coalesceAsync(`${_cacheId}::${key}`, async () => {
274
280
  let value;
281
+ let rawData;
275
282
  let i = 0;
276
283
  let remainingTtl;
284
+ const { ttl: ttl2, refreshThreshold, raw } = isObject(ttlOrOptions) ? ttlOrOptions : { ttl: ttlOrOptions, refreshThreshold: refreshThresholdParameter };
285
+ const resolveTtl = (result) => runIfFn(ttl2, result) ?? options?.ttl;
277
286
  for (; i < stores.length; i++) {
278
287
  try {
279
288
  const data = await stores[i].get(key, { raw: true });
280
289
  if (data !== void 0) {
281
290
  value = data.value;
291
+ rawData = data;
282
292
  if (typeof data.expires === "number") {
283
293
  remainingTtl = Math.max(0, data.expires - Date.now());
284
294
  }
@@ -289,15 +299,15 @@ var createCache = (options) => {
289
299
  }
290
300
  if (value === void 0) {
291
301
  const result = await fnc();
292
- await set(stores, key, result, runIfFn(ttl2, result) ?? options?.ttl);
293
- return result;
302
+ const ttl3 = resolveTtl(result);
303
+ await set(stores, key, result, ttl3);
304
+ return raw ? { value: result, expires: Date.now() + ttl3 } : result;
294
305
  }
295
- const ms = runIfFn(ttl2, value) ?? options?.ttl;
296
- const shouldRefresh = lt(remainingTtl, refreshThreshold ?? options?.refreshThreshold);
306
+ const shouldRefresh = lt(remainingTtl, runIfFn(refreshThreshold, value) ?? options?.refreshThreshold);
297
307
  if (shouldRefresh) {
298
- coalesceAsync(`+++${key}`, fnc).then(async (result) => {
308
+ coalesceAsync(`+++${_cacheId}__${key}`, fnc).then(async (result) => {
299
309
  try {
300
- await set(options?.refreshAllStores ? stores : stores.slice(0, i + 1), key, result, ms);
310
+ await set(options?.refreshAllStores ? stores : stores.slice(0, i + 1), key, result, resolveTtl(result));
301
311
  eventEmitter.emit("refresh", { key, value: result });
302
312
  } catch (error) {
303
313
  eventEmitter.emit("refresh", { key, value, error });
@@ -307,9 +317,9 @@ var createCache = (options) => {
307
317
  });
308
318
  }
309
319
  if (!shouldRefresh && i > 0) {
310
- await set(stores.slice(0, i), key, value, ms);
320
+ await set(stores.slice(0, i), key, value, resolveTtl(value));
311
321
  }
312
- return value;
322
+ return raw ? rawData : value;
313
323
  });
314
324
  const on = (event, listener) => eventEmitter.addListener(event, listener);
315
325
  const off = (event, listener) => eventEmitter.removeListener(event, listener);
@@ -320,6 +330,7 @@ var createCache = (options) => {
320
330
  return Promise.reject(error);
321
331
  }
322
332
  };
333
+ const cacheId = () => _cacheId;
323
334
  return {
324
335
  get,
325
336
  mget,
@@ -332,7 +343,9 @@ var createCache = (options) => {
332
343
  wrap,
333
344
  on,
334
345
  off,
335
- disconnect
346
+ disconnect,
347
+ cacheId,
348
+ stores
336
349
  };
337
350
  };
338
351
  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.1",
4
4
  "description": "Cache Manager for Node.js",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -50,20 +50,20 @@
50
50
  ],
51
51
  "license": "MIT",
52
52
  "dependencies": {
53
- "keyv": "^5.2.3"
53
+ "keyv": "^5.3.1"
54
54
  },
55
55
  "devDependencies": {
56
- "@faker-js/faker": "^9.3.0",
57
- "@keyv/redis": "^4.2.0",
58
- "@types/node": "^22.10.2",
59
- "@vitest/coverage-v8": "^2.1.8",
56
+ "@faker-js/faker": "^9.5.1",
57
+ "@keyv/redis": "^4.3.1",
58
+ "@types/node": "^22.13.9",
59
+ "@vitest/coverage-v8": "^3.0.7",
60
60
  "cache-manager-redis-yet": "^5.1.5",
61
61
  "rimraf": "^6.0.1",
62
- "tsup": "^8.3.5",
63
- "typescript": "^5.7.2",
64
- "vitest": "^2.1.8",
62
+ "tsup": "^8.4.0",
63
+ "typescript": "^5.8.2",
64
+ "vitest": "^3.0.7",
65
65
  "xo": "^0.60.0",
66
- "cacheable": "^1.8.6"
66
+ "cacheable": "^1.8.9"
67
67
  },
68
68
  "xo": {
69
69
  "rules": {