cache-manager 5.6.1 → 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
@@ -3,10 +3,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.createCache = exports.caching = void 0;
6
+ exports.createCache = exports.caching = exports.defaultWrapOptions = void 0;
7
7
  const eventemitter3_1 = __importDefault(require("eventemitter3"));
8
8
  const promise_coalesce_1 = require("promise-coalesce");
9
9
  const index_js_1 = require("./stores/index.js");
10
+ const utils_js_1 = require("./utils.js");
11
+ exports.defaultWrapOptions = {
12
+ nonBlockingSet: false,
13
+ };
10
14
  /**
11
15
  * Generic caching interface that wraps any caching library with a compatible interface.
12
16
  */
@@ -38,22 +42,24 @@ function createCache(store, arguments_) {
38
42
  * const result = await cache.wrap('key', () => Promise.resolve(1));
39
43
  *
40
44
  */
41
- 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 };
42
48
  const refreshThresholdConfig = refreshThreshold ?? arguments_?.refreshThreshold ?? 0;
43
49
  return (0, promise_coalesce_1.coalesceAsync)(key, async () => {
44
50
  const value = await store.get(key).catch(error => {
45
- const errorEvent = { error, key, operation: 'wrap' };
51
+ const errorEvent = { error, key, operation: 'get' };
46
52
  eventEmitter.emit('error', errorEvent);
47
53
  });
48
54
  if (value === undefined) {
49
55
  const result = await function_();
50
56
  const cacheTtl = typeof ttl === 'function' ? ttl(result) : ttl;
51
- await store.set(key, result, cacheTtl).catch(error => {
57
+ await (0, utils_js_1.conditionalAwait)(async () => store.set(key, result, cacheTtl).catch(error => {
52
58
  const errorEvent = {
53
- error, key, operation: 'wrap', data: result,
59
+ error, key, operation: 'set', data: result,
54
60
  };
55
61
  eventEmitter.emit('error', errorEvent);
56
- });
62
+ }), !options_.nonBlockingSet);
57
63
  return result;
58
64
  }
59
65
  if (refreshThresholdConfig) {
@@ -64,7 +70,7 @@ function createCache(store, arguments_) {
64
70
  .then(async (result) => store.set(key, result, cacheTtl))
65
71
  .catch(async (error) => {
66
72
  const errorEvent = {
67
- error, key, operation: 'wrap', data: value,
73
+ error, key, operation: 'set', data: value,
68
74
  };
69
75
  eventEmitter.emit('error', errorEvent);
70
76
  eventEmitter.emit('onBackgroundRefreshError', error);
@@ -5,6 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.multiCaching = void 0;
7
7
  const eventemitter3_1 = __importDefault(require("eventemitter3"));
8
+ const caching_js_1 = require("./caching.js");
9
+ const utils_js_1 = require("./utils.js");
8
10
  /**
9
11
  * Module that lets you specify a hierarchy of caches.
10
12
  */
@@ -28,8 +30,8 @@ function multiCaching(caches) {
28
30
  }
29
31
  }
30
32
  };
31
- const set = async (key, data, ttl) => {
32
- 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 => {
33
35
  const errorEvent = {
34
36
  error, key, operation: 'set', data,
35
37
  };
@@ -38,14 +40,18 @@ function multiCaching(caches) {
38
40
  };
39
41
  return {
40
42
  get,
41
- set,
43
+ async set(key, value, ttl) {
44
+ await set(key, value, ttl);
45
+ },
42
46
  async del(key) {
43
47
  await Promise.all(caches.map(async (cache) => cache.del(key))).catch(error => {
44
48
  const errorEvent = { error, key, operation: 'del' };
45
49
  eventEmitter.emit('error', errorEvent);
46
50
  });
47
51
  },
48
- 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 };
49
55
  let value;
50
56
  let i = 0;
51
57
  for (; i < caches.length; i++) {
@@ -57,24 +63,18 @@ function multiCaching(caches) {
57
63
  }
58
64
  }
59
65
  catch (error) {
60
- const errorEvent = { error, key, operation: 'wrap' };
66
+ const errorEvent = { error, key, operation: 'get' };
61
67
  eventEmitter.emit('error', errorEvent);
62
68
  }
63
69
  }
64
70
  if (value === undefined) {
65
71
  const result = await function_();
66
72
  const cacheTtl = typeof ttl === 'function' ? ttl(result) : ttl;
67
- await set(key, result, cacheTtl);
73
+ await (0, utils_js_1.conditionalAwait)(async () => set(key, result, cacheTtl), !options_.nonBlockingSet);
68
74
  return result;
69
75
  }
70
76
  const cacheTtl = typeof ttl === 'function' ? ttl(value) : ttl;
71
- await Promise.all(caches.slice(0, i).map(async (cache) => cache.set(key, value, cacheTtl))).then().catch(error => {
72
- const errorEvent = {
73
- error, key, operation: 'wrap', data: value,
74
- };
75
- eventEmitter.emit('error', errorEvent);
76
- });
77
- 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);
78
78
  return value;
79
79
  },
80
80
  async reset() {
@@ -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.1",
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",