cache-manager 5.5.2 → 5.6.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/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ MIT License
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to
5
+ deal in the Software without restriction, including without limitation the
6
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7
+ sell copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19
+ DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -18,6 +18,7 @@ A cache module for nodejs that allows easy wrapping of functions in cache, tiere
18
18
  * [Cache Manager Options](#cache-manager-options)
19
19
  * [Refresh cache keys in background](#refresh-cache-keys-in-background)
20
20
  * [Error Handling](#error-handling)
21
+ * [Express Middleware](#express-middleware)
21
22
  * [Store Engines](#store-engines)
22
23
  * [Contribute](#contribute)
23
24
  * [License](#license)
@@ -87,8 +88,6 @@ console.log(await memoryCache.store.mget('foo', 'foo2'));
87
88
  await memoryCache.store.mdel('foo', 'foo2');
88
89
  ```
89
90
 
90
- #### [Example Express App Usage](./examples/express/src/index.mts)
91
-
92
91
  #### Custom Stores
93
92
 
94
93
  You can use your own custom store by creating one with the same API as the built-in memory stores.
@@ -104,13 +103,13 @@ As `caching()` requires async functionality to resolve some stores, this is not
104
103
  If you need to create a cache store synchronously, you can instead use `createCache()`:
105
104
 
106
105
  ```typescript
107
- import { createCache, memoryStore } from 'node-cache-manager';
106
+ import { createCache, memoryStore } from 'cache-manager';
108
107
 
109
108
  // Create memory cache synchronously
110
- const memoryCache = createCache(memoryStore(), {
109
+ const memoryCache = createCache(memoryStore({
111
110
  max: 100,
112
111
  ttl: 10 * 1000 /*milliseconds*/,
113
- });
112
+ }));
114
113
 
115
114
  // Default parameter in function
116
115
  function myService(cache = createCache(memoryStore())) {}
@@ -233,6 +232,62 @@ multicache.on('error', (error) => {
233
232
  });
234
233
  ```
235
234
 
235
+ ## Express Middleware
236
+
237
+ 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.
238
+
239
+ ```typescript
240
+ // The code imports the necessary modules using ES module syntax:
241
+ import { caching } from 'cache-manager';
242
+ import express from 'express';
243
+
244
+ // The memory cache is initialized using cache-manager with a maximum of 100 items and a TTL (time-to-live) of 10 seconds:
245
+ const memoryCache = await caching('memory', {
246
+ max: 100,
247
+ ttl: 10 /* seconds */
248
+ });
249
+
250
+ const app = express();
251
+ const port = 3000;
252
+
253
+ // A middleware function is defined to check the cache before processing the request. If the response is found in the cache, it is returned immediately. If not, the request proceeds to the route handler, and the response is cached before being sent:
254
+ const cacheMiddleware = async (req, res, next) => {
255
+ const key = req.originalUrl;
256
+
257
+ try {
258
+ const cachedResponse = await memoryCache.get(key);
259
+ if (cachedResponse) {
260
+ // Cache hit, return the cached response
261
+ return res.send(cachedResponse);
262
+ } else {
263
+ // Cache miss, proceed to the route handler
264
+ res.sendResponse = res.send;
265
+ res.send = async (body) => {
266
+ // Store the response in cache
267
+ await memoryCache.set(key, body);
268
+ res.sendResponse(body);
269
+ };
270
+ next();
271
+ }
272
+ } catch (err) {
273
+ next(err);
274
+ }
275
+ };
276
+
277
+ // The cacheMiddleware is applied to the /data route, which simulates a slow database call with a 2-second delay:
278
+ app.get('/data', cacheMiddleware, (req, res) => {
279
+ // Simulate a slow database call
280
+ setTimeout(() => {
281
+ res.send({ data: 'This is some data', timestamp: new Date() });
282
+ }, 2000); // 2 seconds delay
283
+ });
284
+
285
+ app.listen(port, () => {
286
+ console.log(`Server is running on http://localhost:${port}`);
287
+ });
288
+
289
+ ```
290
+
236
291
  ## Store Engines
237
292
 
238
293
  ### Official and updated to last version
package/dist/caching.d.ts CHANGED
@@ -27,13 +27,26 @@ export type FactoryStore<S extends Store, T extends Record<string, unknown> = ne
27
27
  export type Stores<S extends Store, T extends Record<string, unknown>> = 'memory' | Store | FactoryStore<S, T>;
28
28
  export type CachingConfig<T> = MemoryConfig | StoreConfig | FactoryConfig<T>;
29
29
  export type WrapTTL<T> = Milliseconds | ((v: T) => Milliseconds);
30
+ export type ErrorEvent<T = never> = {
31
+ operation: 'get' | 'set' | 'del' | 'wrap' | 'reset';
32
+ error: unknown;
33
+ key?: string;
34
+ data?: T;
35
+ } | {
36
+ operation: 'mget' | 'mset' | 'mdel';
37
+ error: unknown;
38
+ keys: string[];
39
+ data?: T[];
40
+ };
41
+ export type ErrorEventHandler<T = unknown> = (event: ErrorEvent<T>) => void;
30
42
  export type Cache<S extends Store = Store> = {
31
43
  store: S;
32
44
  set: (key: string, value: unknown, ttl?: Milliseconds) => Promise<void>;
33
45
  get: <T>(key: string) => Promise<T | undefined>;
34
46
  del: (key: string) => Promise<void>;
35
47
  reset: () => Promise<void>;
36
- on: (event: 'error', handler: (error: Error) => void) => void;
48
+ on: <T>(event: 'error', handler: ErrorEventHandler<T>) => void;
49
+ removeListener: <T>(event: 'error', handler: ErrorEventHandler<T>) => void;
37
50
  wrap<T>(key: string, function_: () => Promise<T>, ttl?: WrapTTL<T>, refreshThreshold?: Milliseconds): Promise<T>;
38
51
  };
39
52
  export declare function caching(name: 'memory', arguments_?: MemoryConfig): Promise<MemoryCache>;
package/dist/caching.js CHANGED
@@ -1,18 +1,12 @@
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 = 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");
1
+ import EventEmitter from 'eventemitter3';
2
+ import { coalesceAsync } from 'promise-coalesce';
3
+ import { memoryStore, } from './stores/index.js';
10
4
  /**
11
5
  * Generic caching interface that wraps any caching library with a compatible interface.
12
6
  */
13
- async function caching(factory, arguments_) {
7
+ export async function caching(factory, arguments_) {
14
8
  if (factory === 'memory') {
15
- const store = (0, index_js_1.memoryStore)(arguments_);
9
+ const store = memoryStore(arguments_);
16
10
  return createCache(store, arguments_);
17
11
  }
18
12
  if (typeof factory === 'function') {
@@ -22,12 +16,11 @@ async function caching(factory, arguments_) {
22
16
  const store = factory;
23
17
  return createCache(store, arguments_);
24
18
  }
25
- exports.caching = caching;
26
19
  /**
27
20
  * Create cache instance by store (non-async).
28
21
  */
29
- function createCache(store, arguments_) {
30
- const eventEmitter = new eventemitter3_1.default();
22
+ export function createCache(store, arguments_) {
23
+ const eventEmitter = new EventEmitter();
31
24
  return {
32
25
  /**
33
26
  * Wraps a function in cache. I.e., the first time the function is run,
@@ -40,24 +33,33 @@ function createCache(store, arguments_) {
40
33
  */
41
34
  async wrap(key, function_, ttl, refreshThreshold) {
42
35
  const refreshThresholdConfig = refreshThreshold ?? arguments_?.refreshThreshold ?? 0;
43
- return (0, promise_coalesce_1.coalesceAsync)(key, async () => {
36
+ return coalesceAsync(key, async () => {
44
37
  const value = await store.get(key).catch(error => {
45
- eventEmitter.emit('error', error);
38
+ const errorEvent = { error, key, operation: 'wrap' };
39
+ eventEmitter.emit('error', errorEvent);
46
40
  });
47
41
  if (value === undefined) {
48
42
  const result = await function_();
49
43
  const cacheTtl = typeof ttl === 'function' ? ttl(result) : ttl;
50
- await store.set(key, result, cacheTtl).catch(error => eventEmitter.emit('error', error));
44
+ await store.set(key, result, cacheTtl).catch(error => {
45
+ const errorEvent = {
46
+ error, key, operation: 'wrap', data: result,
47
+ };
48
+ eventEmitter.emit('error', errorEvent);
49
+ });
51
50
  return result;
52
51
  }
53
52
  if (refreshThresholdConfig) {
54
53
  const cacheTtl = typeof ttl === 'function' ? ttl(value) : ttl;
55
54
  const remainingTtl = await store.ttl(key);
56
55
  if (remainingTtl !== -1 && remainingTtl < refreshThresholdConfig) {
57
- (0, promise_coalesce_1.coalesceAsync)(`+++${key}`, function_)
56
+ coalesceAsync(`+++${key}`, function_)
58
57
  .then(async (result) => store.set(key, result, cacheTtl))
59
58
  .catch(async (error) => {
60
- eventEmitter.emit('error', error);
59
+ const errorEvent = {
60
+ error, key, operation: 'wrap', data: value,
61
+ };
62
+ eventEmitter.emit('error', errorEvent);
61
63
  eventEmitter.emit('onBackgroundRefreshError', error);
62
64
  if (arguments_?.onBackgroundRefreshError) {
63
65
  arguments_.onBackgroundRefreshError(error);
@@ -78,7 +80,7 @@ function createCache(store, arguments_) {
78
80
  set: async (key, value, ttl) => store.set(key, value, ttl),
79
81
  reset: async () => store.reset(),
80
82
  on: (event, handler) => eventEmitter.on('error', handler),
83
+ removeListener: (event, handler) => eventEmitter.removeListener(event, handler),
81
84
  };
82
85
  }
83
- exports.createCache = createCache;
84
86
  //# sourceMappingURL=caching.js.map
package/dist/index.js CHANGED
@@ -1,20 +1,4 @@
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);
1
+ export * from './caching.js';
2
+ export * from './multi-caching.js';
3
+ export * from './stores/index.js';
20
4
  //# sourceMappingURL=index.js.map
@@ -1,15 +1,12 @@
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"));
1
+ import EventEmitter from 'eventemitter3';
8
2
  /**
9
3
  * Module that lets you specify a hierarchy of caches.
10
4
  */
11
- function multiCaching(caches) {
12
- const eventEmitter = new eventemitter3_1.default();
5
+ export function multiCaching(caches) {
6
+ const eventEmitter = new EventEmitter();
7
+ for (const cache of caches) {
8
+ cache.on('error', event => eventEmitter.emit('error', event));
9
+ }
13
10
  const get = async (key) => {
14
11
  for (const cache of caches) {
15
12
  try {
@@ -20,18 +17,27 @@ function multiCaching(caches) {
20
17
  }
21
18
  }
22
19
  catch (error) {
23
- eventEmitter.emit('error', error);
20
+ const errorEvent = { error, key, operation: 'get' };
21
+ eventEmitter.emit('error', errorEvent);
24
22
  }
25
23
  }
26
24
  };
27
25
  const set = async (key, data, ttl) => {
28
- await Promise.all(caches.map(async (cache) => cache.set(key, data, ttl))).catch(error => eventEmitter.emit('error', error));
26
+ await Promise.all(caches.map(async (cache) => cache.set(key, data, ttl))).catch(error => {
27
+ const errorEvent = {
28
+ error, key, operation: 'set', data,
29
+ };
30
+ eventEmitter.emit('error', errorEvent);
31
+ });
29
32
  };
30
33
  return {
31
34
  get,
32
35
  set,
33
36
  async del(key) {
34
- await Promise.all(caches.map(async (cache) => cache.del(key))).catch(error => eventEmitter.emit('error', error));
37
+ await Promise.all(caches.map(async (cache) => cache.del(key))).catch(error => {
38
+ const errorEvent = { error, key, operation: 'del' };
39
+ eventEmitter.emit('error', errorEvent);
40
+ });
35
41
  },
36
42
  async wrap(key, function_, ttl, refreshThreshold) {
37
43
  let value;
@@ -45,7 +51,8 @@ function multiCaching(caches) {
45
51
  }
46
52
  }
47
53
  catch (error) {
48
- eventEmitter.emit('error', error);
54
+ const errorEvent = { error, key, operation: 'wrap' };
55
+ eventEmitter.emit('error', errorEvent);
49
56
  }
50
57
  }
51
58
  if (value === undefined) {
@@ -55,12 +62,20 @@ function multiCaching(caches) {
55
62
  return result;
56
63
  }
57
64
  const cacheTtl = typeof ttl === 'function' ? ttl(value) : ttl;
58
- await Promise.all(caches.slice(0, i).map(async (cache) => cache.set(key, value, cacheTtl))).then().catch(error => eventEmitter.emit('error', error));
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
+ });
59
71
  await caches[i].wrap(key, function_, ttl, refreshThreshold).then(); // Call wrap for store for internal refreshThreshold logic, see: src/caching.ts caching.wrap
60
72
  return value;
61
73
  },
62
74
  async reset() {
63
- await Promise.all(caches.map(async (x) => x.reset())).catch(error => eventEmitter.emit('error', error));
75
+ await Promise.all(caches.map(async (x) => x.reset())).catch(error => {
76
+ const errorEvent = { error, key: '', operation: 'reset' };
77
+ eventEmitter.emit('error', errorEvent);
78
+ });
64
79
  },
65
80
  async mget(...keys) {
66
81
  const values = Array.from({ length: keys.length }).fill(undefined);
@@ -78,20 +93,31 @@ function multiCaching(caches) {
78
93
  }
79
94
  }
80
95
  catch (error) {
81
- eventEmitter.emit('error', error);
96
+ const errorEvent = { error, keys, operation: 'mget' };
97
+ eventEmitter.emit('error', errorEvent);
82
98
  }
83
99
  }
84
100
  return values;
85
101
  },
86
102
  async mset(arguments_, ttl) {
87
- await Promise.all(caches.map(async (cache) => cache.store.mset(arguments_, ttl))).catch(error => eventEmitter.emit('error', error));
103
+ await Promise.all(caches.map(async (cache) => cache.store.mset(arguments_, ttl))).catch(error => {
104
+ const keys = arguments_.map(([key]) => key);
105
+ const data = arguments_.map(([, value]) => value);
106
+ const errorEvent = {
107
+ error, keys, data, operation: 'mset',
108
+ };
109
+ eventEmitter.emit('error', errorEvent);
110
+ });
88
111
  },
89
112
  async mdel(...keys) {
90
113
  await Promise.all(caches.map(async (cache) => cache.store.mdel(...keys)))
91
- .catch(error => eventEmitter.emit('error', error));
114
+ .catch(error => {
115
+ const errorEvent = { error, keys, operation: 'mdel' };
116
+ eventEmitter.emit('error', errorEvent);
117
+ });
92
118
  },
93
119
  on: (event, handler) => eventEmitter.on('error', handler),
120
+ removeListener: (event, handler) => eventEmitter.removeListener(event, handler),
94
121
  };
95
122
  }
96
- exports.multiCaching = multiCaching;
97
123
  //# sourceMappingURL=multi-caching.js.map
@@ -1,18 +1,2 @@
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);
1
+ export * from './memory.js';
18
2
  //# sourceMappingURL=index.js.map
@@ -1,21 +1,15 @@
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"));
1
+ import { LRUCache } from 'lru-cache';
2
+ import cloneDeep from 'lodash.clonedeep';
9
3
  function clone(object) {
10
4
  if (typeof object === 'object' && object !== null) {
11
- return (0, lodash_clonedeep_1.default)(object);
5
+ return cloneDeep(object);
12
6
  }
13
7
  return object;
14
8
  }
15
9
  /**
16
10
  * Wrapper for lru-cache.
17
11
  */
18
- function memoryStore(arguments_) {
12
+ export function memoryStore(arguments_) {
19
13
  const shouldCloneBeforeSet = arguments_?.shouldCloneBeforeSet !== false; // Clone by default
20
14
  const isCacheable = arguments_?.isCacheable ?? (value => value !== undefined);
21
15
  const lruOptions = {
@@ -24,7 +18,7 @@ function memoryStore(arguments_) {
24
18
  max: arguments_?.max ?? 500,
25
19
  ttl: arguments_?.ttl === undefined ? 0 : arguments_.ttl,
26
20
  };
27
- const lruCache = new lru_cache_1.LRUCache(lruOptions);
21
+ const lruCache = new LRUCache(lruOptions);
28
22
  return {
29
23
  async del(key) {
30
24
  lruCache.delete(key);
@@ -87,5 +81,4 @@ function memoryStore(arguments_) {
87
81
  },
88
82
  };
89
83
  }
90
- exports.memoryStore = memoryStore;
91
84
  //# sourceMappingURL=memory.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cache-manager",
3
- "version": "5.5.2",
3
+ "version": "5.6.0",
4
4
  "description": "Cache module for Node.js",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -8,12 +8,8 @@
8
8
  "dist/**/*.js",
9
9
  "dist/**/*.d.ts"
10
10
  ],
11
- "scripts": {
12
- "build": "tsc -p tsconfig.build.json",
13
- "clean": "rimraf ./dist ./coverage ./node_modules ./package-lock.json ./yarn.lock ./pnpm-lock.yaml",
14
- "test": "xo --fix && vitest run --coverage",
15
- "test:ci": "xo && vitest run",
16
- "prepare": "pnpm build"
11
+ "engines": {
12
+ "node": ">= 18"
17
13
  },
18
14
  "repository": {
19
15
  "type": "git",
@@ -49,14 +45,14 @@
49
45
  "devDependencies": {
50
46
  "@faker-js/faker": "^8.4.1",
51
47
  "@types/lodash.clonedeep": "^4.5.9",
52
- "@types/node": "^20.12.7",
53
- "@typescript-eslint/eslint-plugin": "^7.7.1",
54
- "@typescript-eslint/parser": "^7.7.1",
55
- "@vitest/coverage-v8": "^1.5.2",
48
+ "@types/node": "^20.12.12",
49
+ "@typescript-eslint/eslint-plugin": "^7.10.0",
50
+ "@typescript-eslint/parser": "^7.10.0",
51
+ "@vitest/coverage-v8": "^1.6.0",
56
52
  "eslint-config-xo-typescript": "^4.0.0",
57
- "rimraf": "^5.0.5",
53
+ "rimraf": "^5.0.7",
58
54
  "typescript": "^5.4.5",
59
- "vitest": "^1.5.2",
55
+ "vitest": "^1.6.0",
60
56
  "xo": "^0.58.0"
61
57
  },
62
58
  "xo": {
@@ -65,5 +61,11 @@
65
61
  "ts",
66
62
  "tsx"
67
63
  ]
64
+ },
65
+ "scripts": {
66
+ "build": "rimraf ./dist && tsc -p tsconfig.build.json",
67
+ "clean": "rimraf ./dist ./coverage ./node_modules ./package-lock.json ./yarn.lock ./pnpm-lock.yaml",
68
+ "test": "xo --fix && vitest run --coverage",
69
+ "test:ci": "xo && vitest run"
68
70
  }
69
- }
71
+ }