cache-manager 5.6.0 → 5.7.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
@@ -232,6 +232,17 @@ multicache.on('error', (error) => {
232
232
  });
233
233
  ```
234
234
 
235
+ ## Using non-blocking set with wrap
236
+ By default, when using `wrap` the value is set in the cache before the function returns.
237
+ While this behaviour can prevent additional calls to downstream resources, it can also slow down the response time.
238
+ This can be changed by setting the `nonBlockingSet` option to `true`.
239
+ Doing will make the function return before the value is set in the cache.
240
+ The setting applies to both single and multi caches.
241
+
242
+ ```typescript
243
+ cache.wrap('key', () => fetchValue(), 1000, 500, {nonBlockingSet: true});
244
+ ```
245
+
235
246
  ## Express Middleware
236
247
 
237
248
  This example sets up an Express application with a caching mechanism using cache-manager. The cacheMiddleware checks if the response for a request is already cached and returns it if available. If not, it proceeds to the route handler, caches the response, and then returns it. This helps to reduce the load on the server by avoiding repeated processing of the same requests.
@@ -244,7 +255,7 @@ import express from 'express';
244
255
  // The memory cache is initialized using cache-manager with a maximum of 100 items and a TTL (time-to-live) of 10 seconds:
245
256
  const memoryCache = await caching('memory', {
246
257
  max: 100,
247
- ttl: 10 /* seconds */
258
+ ttl: 10 * 1000 /*milliseconds*/
248
259
  });
249
260
 
250
261
  const app = express();
package/dist/caching.d.ts CHANGED
@@ -28,7 +28,7 @@ export type Stores<S extends Store, T extends Record<string, unknown>> = 'memory
28
28
  export type CachingConfig<T> = MemoryConfig | StoreConfig | FactoryConfig<T>;
29
29
  export type WrapTTL<T> = Milliseconds | ((v: T) => Milliseconds);
30
30
  export type ErrorEvent<T = never> = {
31
- operation: 'get' | 'set' | 'del' | 'wrap' | 'reset';
31
+ operation: 'get' | 'set' | 'del' | 'reset';
32
32
  error: unknown;
33
33
  key?: string;
34
34
  data?: T;
@@ -47,8 +47,12 @@ export type Cache<S extends Store = Store> = {
47
47
  reset: () => Promise<void>;
48
48
  on: <T>(event: 'error', handler: ErrorEventHandler<T>) => void;
49
49
  removeListener: <T>(event: 'error', handler: ErrorEventHandler<T>) => void;
50
- wrap<T>(key: string, function_: () => Promise<T>, ttl?: WrapTTL<T>, refreshThreshold?: Milliseconds): Promise<T>;
50
+ wrap<T>(key: string, function_: () => Promise<T>, ttl?: WrapTTL<T>, refreshThreshold?: Milliseconds, options?: WrapOptions): Promise<T>;
51
51
  };
52
+ export type WrapOptions = {
53
+ nonBlockingSet?: boolean;
54
+ };
55
+ export declare const defaultWrapOptions: WrapOptions;
52
56
  export declare function caching(name: 'memory', arguments_?: MemoryConfig): Promise<MemoryCache>;
53
57
  export declare function caching<S extends Store>(store: S): Promise<Cache<S>>;
54
58
  export declare function caching<S extends Store, T extends Record<string, unknown> = never>(factory: FactoryStore<S, T>, arguments_?: FactoryConfig<T>): Promise<Cache<S>>;
package/dist/caching.js CHANGED
@@ -1,12 +1,22 @@
1
- import EventEmitter from 'eventemitter3';
2
- import { coalesceAsync } from 'promise-coalesce';
3
- import { memoryStore, } from './stores/index.js';
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createCache = exports.caching = exports.defaultWrapOptions = void 0;
7
+ const eventemitter3_1 = __importDefault(require("eventemitter3"));
8
+ const promise_coalesce_1 = require("promise-coalesce");
9
+ const index_js_1 = require("./stores/index.js");
10
+ const utils_js_1 = require("./utils.js");
11
+ exports.defaultWrapOptions = {
12
+ nonBlockingSet: false,
13
+ };
4
14
  /**
5
15
  * Generic caching interface that wraps any caching library with a compatible interface.
6
16
  */
7
- export async function caching(factory, arguments_) {
17
+ async function caching(factory, arguments_) {
8
18
  if (factory === 'memory') {
9
- const store = memoryStore(arguments_);
19
+ const store = (0, index_js_1.memoryStore)(arguments_);
10
20
  return createCache(store, arguments_);
11
21
  }
12
22
  if (typeof factory === 'function') {
@@ -16,11 +26,12 @@ export async function caching(factory, arguments_) {
16
26
  const store = factory;
17
27
  return createCache(store, arguments_);
18
28
  }
29
+ exports.caching = caching;
19
30
  /**
20
31
  * Create cache instance by store (non-async).
21
32
  */
22
- export function createCache(store, arguments_) {
23
- const eventEmitter = new EventEmitter();
33
+ function createCache(store, arguments_) {
34
+ const eventEmitter = new eventemitter3_1.default();
24
35
  return {
25
36
  /**
26
37
  * Wraps a function in cache. I.e., the first time the function is run,
@@ -31,33 +42,35 @@ export function createCache(store, arguments_) {
31
42
  * const result = await cache.wrap('key', () => Promise.resolve(1));
32
43
  *
33
44
  */
34
- async wrap(key, function_, ttl, refreshThreshold) {
45
+ // eslint-disable-next-line max-params
46
+ async wrap(key, function_, ttl, refreshThreshold, options = {}) {
47
+ const options_ = { ...exports.defaultWrapOptions, ...options };
35
48
  const refreshThresholdConfig = refreshThreshold ?? arguments_?.refreshThreshold ?? 0;
36
- return coalesceAsync(key, async () => {
49
+ return (0, promise_coalesce_1.coalesceAsync)(key, async () => {
37
50
  const value = await store.get(key).catch(error => {
38
- const errorEvent = { error, key, operation: 'wrap' };
51
+ const errorEvent = { error, key, operation: 'get' };
39
52
  eventEmitter.emit('error', errorEvent);
40
53
  });
41
54
  if (value === undefined) {
42
55
  const result = await function_();
43
56
  const cacheTtl = typeof ttl === 'function' ? ttl(result) : ttl;
44
- await store.set(key, result, cacheTtl).catch(error => {
57
+ await (0, utils_js_1.conditionalAwait)(async () => store.set(key, result, cacheTtl).catch(error => {
45
58
  const errorEvent = {
46
- error, key, operation: 'wrap', data: result,
59
+ error, key, operation: 'set', data: result,
47
60
  };
48
61
  eventEmitter.emit('error', errorEvent);
49
- });
62
+ }), !options_.nonBlockingSet);
50
63
  return result;
51
64
  }
52
65
  if (refreshThresholdConfig) {
53
66
  const cacheTtl = typeof ttl === 'function' ? ttl(value) : ttl;
54
67
  const remainingTtl = await store.ttl(key);
55
68
  if (remainingTtl !== -1 && remainingTtl < refreshThresholdConfig) {
56
- coalesceAsync(`+++${key}`, function_)
69
+ (0, promise_coalesce_1.coalesceAsync)(`+++${key}`, function_)
57
70
  .then(async (result) => store.set(key, result, cacheTtl))
58
71
  .catch(async (error) => {
59
72
  const errorEvent = {
60
- error, key, operation: 'wrap', data: value,
73
+ error, key, operation: 'set', data: value,
61
74
  };
62
75
  eventEmitter.emit('error', errorEvent);
63
76
  eventEmitter.emit('onBackgroundRefreshError', error);
@@ -83,4 +96,5 @@ export function createCache(store, arguments_) {
83
96
  removeListener: (event, handler) => eventEmitter.removeListener(event, handler),
84
97
  };
85
98
  }
99
+ exports.createCache = createCache;
86
100
  //# sourceMappingURL=caching.js.map
package/dist/index.js CHANGED
@@ -1,4 +1,20 @@
1
- export * from './caching.js';
2
- export * from './multi-caching.js';
3
- export * from './stores/index.js';
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
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./caching.js"), exports);
18
+ __exportStar(require("./multi-caching.js"), exports);
19
+ __exportStar(require("./stores/index.js"), exports);
4
20
  //# sourceMappingURL=index.js.map
@@ -1,9 +1,17 @@
1
- import EventEmitter from 'eventemitter3';
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.multiCaching = void 0;
7
+ const eventemitter3_1 = __importDefault(require("eventemitter3"));
8
+ const caching_js_1 = require("./caching.js");
9
+ const utils_js_1 = require("./utils.js");
2
10
  /**
3
11
  * Module that lets you specify a hierarchy of caches.
4
12
  */
5
- export function multiCaching(caches) {
6
- const eventEmitter = new EventEmitter();
13
+ function multiCaching(caches) {
14
+ const eventEmitter = new eventemitter3_1.default();
7
15
  for (const cache of caches) {
8
16
  cache.on('error', event => eventEmitter.emit('error', event));
9
17
  }
@@ -22,8 +30,8 @@ export function multiCaching(caches) {
22
30
  }
23
31
  }
24
32
  };
25
- const set = async (key, data, ttl) => {
26
- await Promise.all(caches.map(async (cache) => cache.set(key, data, ttl))).catch(error => {
33
+ const set = async (key, data, ttl, slice = caches.length) => {
34
+ await Promise.all(caches.slice(0, slice).map(async (cache) => cache.set(key, data, ttl))).catch(error => {
27
35
  const errorEvent = {
28
36
  error, key, operation: 'set', data,
29
37
  };
@@ -32,14 +40,18 @@ export function multiCaching(caches) {
32
40
  };
33
41
  return {
34
42
  get,
35
- set,
43
+ async set(key, value, ttl) {
44
+ await set(key, value, ttl);
45
+ },
36
46
  async del(key) {
37
47
  await Promise.all(caches.map(async (cache) => cache.del(key))).catch(error => {
38
48
  const errorEvent = { error, key, operation: 'del' };
39
49
  eventEmitter.emit('error', errorEvent);
40
50
  });
41
51
  },
42
- async wrap(key, function_, ttl, refreshThreshold) {
52
+ // eslint-disable-next-line max-params
53
+ async wrap(key, function_, ttl, refreshThreshold, options = {}) {
54
+ const options_ = { ...caching_js_1.defaultWrapOptions, ...options };
43
55
  let value;
44
56
  let i = 0;
45
57
  for (; i < caches.length; i++) {
@@ -51,24 +63,18 @@ export function multiCaching(caches) {
51
63
  }
52
64
  }
53
65
  catch (error) {
54
- const errorEvent = { error, key, operation: 'wrap' };
66
+ const errorEvent = { error, key, operation: 'get' };
55
67
  eventEmitter.emit('error', errorEvent);
56
68
  }
57
69
  }
58
70
  if (value === undefined) {
59
71
  const result = await function_();
60
72
  const cacheTtl = typeof ttl === 'function' ? ttl(result) : ttl;
61
- await set(key, result, cacheTtl);
73
+ await (0, utils_js_1.conditionalAwait)(async () => set(key, result, cacheTtl), !options_.nonBlockingSet);
62
74
  return result;
63
75
  }
64
76
  const cacheTtl = typeof ttl === 'function' ? ttl(value) : ttl;
65
- await Promise.all(caches.slice(0, i).map(async (cache) => cache.set(key, value, cacheTtl))).then().catch(error => {
66
- const errorEvent = {
67
- error, key, operation: 'wrap', data: value,
68
- };
69
- eventEmitter.emit('error', errorEvent);
70
- });
71
- await caches[i].wrap(key, function_, ttl, refreshThreshold).then(); // Call wrap for store for internal refreshThreshold logic, see: src/caching.ts caching.wrap
77
+ await (0, utils_js_1.conditionalAwait)(async () => set(key, value, cacheTtl, i).then(async () => caches[i].wrap(key, function_, ttl, refreshThreshold)), !options_.nonBlockingSet);
72
78
  return value;
73
79
  },
74
80
  async reset() {
@@ -120,4 +126,5 @@ export function multiCaching(caches) {
120
126
  removeListener: (event, handler) => eventEmitter.removeListener(event, handler),
121
127
  };
122
128
  }
129
+ exports.multiCaching = multiCaching;
123
130
  //# sourceMappingURL=multi-caching.js.map
@@ -1,2 +1,18 @@
1
- export * from './memory.js';
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
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./memory.js"), exports);
2
18
  //# sourceMappingURL=index.js.map
@@ -1,15 +1,21 @@
1
- import { LRUCache } from 'lru-cache';
2
- import cloneDeep from 'lodash.clonedeep';
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.memoryStore = void 0;
7
+ const lru_cache_1 = require("lru-cache");
8
+ const lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep"));
3
9
  function clone(object) {
4
10
  if (typeof object === 'object' && object !== null) {
5
- return cloneDeep(object);
11
+ return (0, lodash_clonedeep_1.default)(object);
6
12
  }
7
13
  return object;
8
14
  }
9
15
  /**
10
16
  * Wrapper for lru-cache.
11
17
  */
12
- export function memoryStore(arguments_) {
18
+ function memoryStore(arguments_) {
13
19
  const shouldCloneBeforeSet = arguments_?.shouldCloneBeforeSet !== false; // Clone by default
14
20
  const isCacheable = arguments_?.isCacheable ?? (value => value !== undefined);
15
21
  const lruOptions = {
@@ -18,7 +24,7 @@ export function memoryStore(arguments_) {
18
24
  max: arguments_?.max ?? 500,
19
25
  ttl: arguments_?.ttl === undefined ? 0 : arguments_.ttl,
20
26
  };
21
- const lruCache = new LRUCache(lruOptions);
27
+ const lruCache = new lru_cache_1.LRUCache(lruOptions);
22
28
  return {
23
29
  async del(key) {
24
30
  lruCache.delete(key);
@@ -81,4 +87,5 @@ export function memoryStore(arguments_) {
81
87
  },
82
88
  };
83
89
  }
90
+ exports.memoryStore = memoryStore;
84
91
  //# sourceMappingURL=memory.js.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * If blocking is true, it will await the function before returning.
3
+ * Otherwise, it will fire the execution and return before it ends.
4
+ * Consumer of this function should await the returned promise.
5
+ * @param function_
6
+ * @param blocking
7
+ */
8
+ export declare const conditionalAwait: (function_: () => Promise<unknown>, blocking: boolean) => Promise<void>;
package/dist/utils.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.conditionalAwait = void 0;
4
+ /**
5
+ * If blocking is true, it will await the function before returning.
6
+ * Otherwise, it will fire the execution and return before it ends.
7
+ * Consumer of this function should await the returned promise.
8
+ * @param function_
9
+ * @param blocking
10
+ */
11
+ const conditionalAwait = async (function_, blocking) => {
12
+ if (blocking) {
13
+ await function_();
14
+ }
15
+ else {
16
+ void function_().then();
17
+ }
18
+ };
19
+ exports.conditionalAwait = conditionalAwait;
20
+ //# sourceMappingURL=utils.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cache-manager",
3
- "version": "5.6.0",
3
+ "version": "5.7.1",
4
4
  "description": "Cache module for Node.js",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -45,9 +45,9 @@
45
45
  "devDependencies": {
46
46
  "@faker-js/faker": "^8.4.1",
47
47
  "@types/lodash.clonedeep": "^4.5.9",
48
- "@types/node": "^20.12.12",
49
- "@typescript-eslint/eslint-plugin": "^7.10.0",
50
- "@typescript-eslint/parser": "^7.10.0",
48
+ "@types/node": "^20.14.2",
49
+ "@typescript-eslint/eslint-plugin": "^7.13.0",
50
+ "@typescript-eslint/parser": "^7.13.0",
51
51
  "@vitest/coverage-v8": "^1.6.0",
52
52
  "eslint-config-xo-typescript": "^4.0.0",
53
53
  "rimraf": "^5.0.7",