cache-manager 5.5.1 → 5.5.3

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
@@ -94,8 +94,8 @@ await memoryCache.store.mdel('foo', 'foo2');
94
94
  You can use your own custom store by creating one with the same API as the built-in memory stores.
95
95
 
96
96
  - [Example Custom Store lru-cache](./src/stores/memory.ts)
97
- - [Example Custom Store redis](https://github.com/node-cache-manager/node-cache-manager-redis-yet)
98
- - [Example Custom Store ioredis](https://github.com/node-cache-manager/node-cache-manager-ioredis-yet)
97
+ - [Example Custom Store redis](https://github.com/jaredwray/cache-manager/packages/cache-manager-redis-yet)
98
+ - [Example Custom Store ioredis](https://github.com/jaredwray/cache-manager/packages/cache-manager-ioredis-yet)
99
99
 
100
100
  #### Create single cache store synchronously
101
101
 
@@ -104,13 +104,13 @@ As `caching()` requires async functionality to resolve some stores, this is not
104
104
  If you need to create a cache store synchronously, you can instead use `createCache()`:
105
105
 
106
106
  ```typescript
107
- import { createCache, memoryStore } from 'node-cache-manager';
107
+ import { createCache, memoryStore } from 'cache-manager';
108
108
 
109
109
  // Create memory cache synchronously
110
- const memoryCache = createCache(memoryStore(), {
110
+ const memoryCache = createCache(memoryStore({
111
111
  max: 100,
112
112
  ttl: 10 * 1000 /*milliseconds*/,
113
- });
113
+ }));
114
114
 
115
115
  // Default parameter in function
116
116
  function myService(cache = createCache(memoryStore())) {}
@@ -170,10 +170,11 @@ See unit tests in [`test/multi-caching.test.ts`](./test/multi-caching.test.ts) f
170
170
 
171
171
  ### Cache Manager Options
172
172
 
173
- The `caching` and `multiCaching` functions accept an options object as the second parameter. The following options are available:
174
- * max: The maximum number of items that can be stored in the cache. If the cache is full, the least recently used item is removed.
173
+ The `caching` function accepts an options object as the second parameter. The following options are available:
175
174
  * ttl: 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.
176
- * shouldCloneBeforeSet: If true, the value will be cloned before being set in the cache. This is set to `true` by default.
175
+ * refreshThreshold: discussed in details below.
176
+ * isCacheable: a function to determine whether the value is cacheable or not.
177
+ * onBackgroundRefreshError: a function to handle errors that occur during background refresh.
177
178
 
178
179
  ```typescript
179
180
  import { caching } from 'cache-manager';
@@ -185,6 +186,10 @@ const memoryCache = await caching('memory', {
185
186
  });
186
187
  ```
187
188
 
189
+ When creating a memory store, you also get these addition options:
190
+ * max: The maximum number of items that can be stored in the cache. If the cache is full, the least recently used item is removed.
191
+ * shouldCloneBeforeSet: If true, the value will be cloned before being set in the cache. This is set to `true` by default.
192
+
188
193
  ### Refresh cache keys in background
189
194
 
190
195
  Both the `caching` and `multicaching` modules support a mechanism to refresh expiring cache keys in background when using the `wrap` function.
@@ -219,14 +224,11 @@ When a value will be retrieved from Redis with a TTL minor than 3sec, the value
219
224
 
220
225
  ## Error Handling
221
226
 
222
- Cache Manager now does not throw errors by default. Instead, all errors are evented through the `error` event. Here is an example on how to use it:
227
+ `multiCaching` now does not throw errors by default. Instead, all errors are evented through the `error` event. Here is an example on how to use it:
223
228
 
224
229
  ```javascript
225
- const memoryCache = await caching('memory', {
226
- max: 100,
227
- ttl: 10 * 1000 /*milliseconds*/,
228
- });
229
- memoryCache.on('error', (error) => {
230
+ const multicache = await multiCaching([memoryCache, someOtherCache]);
231
+ multicache.on('error', (error) => {
230
232
  console.error('Cache error:', error);
231
233
  });
232
234
  ```
@@ -235,9 +237,9 @@ memoryCache.on('error', (error) => {
235
237
 
236
238
  ### Official and updated to last version
237
239
 
238
- - [node-cache-manager-redis-yet](https://github.com/node-cache-manager/node-cache-manager-redis-yet) (uses [node_redis](https://github.com/NodeRedis/node_redis))
240
+ - [node-cache-manager-redis-yet](https://github.com/jaredwray/cache-manager/packages/cache-manager-redis-yet) (uses [node_redis](https://github.com/NodeRedis/node_redis))
239
241
 
240
- - [node-cache-manager-ioredis-yet](https://github.com/node-cache-manager/node-cache-manager-ioredis-yet) (uses [ioredis](https://github.com/luin/ioredis))
242
+ - [node-cache-manager-ioredis-yet](https://github.com/jaredwray/cache-manager/packages/cache-manager-ioredis-yet) (uses [ioredis](https://github.com/luin/ioredis))
241
243
 
242
244
  ### Third party
243
245
 
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
@@ -42,12 +42,18 @@ function createCache(store, arguments_) {
42
42
  const refreshThresholdConfig = refreshThreshold ?? arguments_?.refreshThreshold ?? 0;
43
43
  return (0, promise_coalesce_1.coalesceAsync)(key, async () => {
44
44
  const value = await store.get(key).catch(error => {
45
- eventEmitter.emit('error', error);
45
+ const errorEvent = { error, key, operation: 'wrap' };
46
+ eventEmitter.emit('error', errorEvent);
46
47
  });
47
48
  if (value === undefined) {
48
49
  const result = await function_();
49
50
  const cacheTtl = typeof ttl === 'function' ? ttl(result) : ttl;
50
- await store.set(key, result, cacheTtl).catch(error => eventEmitter.emit('error', error));
51
+ await store.set(key, result, cacheTtl).catch(error => {
52
+ const errorEvent = {
53
+ error, key, operation: 'wrap', data: result,
54
+ };
55
+ eventEmitter.emit('error', errorEvent);
56
+ });
51
57
  return result;
52
58
  }
53
59
  if (refreshThresholdConfig) {
@@ -57,7 +63,10 @@ function createCache(store, arguments_) {
57
63
  (0, promise_coalesce_1.coalesceAsync)(`+++${key}`, function_)
58
64
  .then(async (result) => store.set(key, result, cacheTtl))
59
65
  .catch(async (error) => {
60
- eventEmitter.emit('error', error);
66
+ const errorEvent = {
67
+ error, key, operation: 'wrap', data: value,
68
+ };
69
+ eventEmitter.emit('error', errorEvent);
61
70
  eventEmitter.emit('onBackgroundRefreshError', error);
62
71
  if (arguments_?.onBackgroundRefreshError) {
63
72
  arguments_.onBackgroundRefreshError(error);
@@ -78,6 +87,7 @@ function createCache(store, arguments_) {
78
87
  set: async (key, value, ttl) => store.set(key, value, ttl),
79
88
  reset: async () => store.reset(),
80
89
  on: (event, handler) => eventEmitter.on('error', handler),
90
+ removeListener: (event, handler) => eventEmitter.removeListener(event, handler),
81
91
  };
82
92
  }
83
93
  exports.createCache = createCache;
@@ -10,6 +10,9 @@ const eventemitter3_1 = __importDefault(require("eventemitter3"));
10
10
  */
11
11
  function multiCaching(caches) {
12
12
  const eventEmitter = new eventemitter3_1.default();
13
+ for (const cache of caches) {
14
+ cache.on('error', event => eventEmitter.emit('error', event));
15
+ }
13
16
  const get = async (key) => {
14
17
  for (const cache of caches) {
15
18
  try {
@@ -20,18 +23,27 @@ function multiCaching(caches) {
20
23
  }
21
24
  }
22
25
  catch (error) {
23
- eventEmitter.emit('error', error);
26
+ const errorEvent = { error, key, operation: 'get' };
27
+ eventEmitter.emit('error', errorEvent);
24
28
  }
25
29
  }
26
30
  };
27
31
  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));
32
+ await Promise.all(caches.map(async (cache) => cache.set(key, data, ttl))).catch(error => {
33
+ const errorEvent = {
34
+ error, key, operation: 'set', data,
35
+ };
36
+ eventEmitter.emit('error', errorEvent);
37
+ });
29
38
  };
30
39
  return {
31
40
  get,
32
41
  set,
33
42
  async del(key) {
34
- await Promise.all(caches.map(async (cache) => cache.del(key))).catch(error => eventEmitter.emit('error', error));
43
+ await Promise.all(caches.map(async (cache) => cache.del(key))).catch(error => {
44
+ const errorEvent = { error, key, operation: 'del' };
45
+ eventEmitter.emit('error', errorEvent);
46
+ });
35
47
  },
36
48
  async wrap(key, function_, ttl, refreshThreshold) {
37
49
  let value;
@@ -45,7 +57,8 @@ function multiCaching(caches) {
45
57
  }
46
58
  }
47
59
  catch (error) {
48
- eventEmitter.emit('error', error);
60
+ const errorEvent = { error, key, operation: 'wrap' };
61
+ eventEmitter.emit('error', errorEvent);
49
62
  }
50
63
  }
51
64
  if (value === undefined) {
@@ -55,12 +68,20 @@ function multiCaching(caches) {
55
68
  return result;
56
69
  }
57
70
  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));
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
+ });
59
77
  await caches[i].wrap(key, function_, ttl, refreshThreshold).then(); // Call wrap for store for internal refreshThreshold logic, see: src/caching.ts caching.wrap
60
78
  return value;
61
79
  },
62
80
  async reset() {
63
- await Promise.all(caches.map(async (x) => x.reset())).catch(error => eventEmitter.emit('error', error));
81
+ await Promise.all(caches.map(async (x) => x.reset())).catch(error => {
82
+ const errorEvent = { error, key: '', operation: 'reset' };
83
+ eventEmitter.emit('error', errorEvent);
84
+ });
64
85
  },
65
86
  async mget(...keys) {
66
87
  const values = Array.from({ length: keys.length }).fill(undefined);
@@ -78,19 +99,31 @@ function multiCaching(caches) {
78
99
  }
79
100
  }
80
101
  catch (error) {
81
- eventEmitter.emit('error', error);
102
+ const errorEvent = { error, keys, operation: 'mget' };
103
+ eventEmitter.emit('error', errorEvent);
82
104
  }
83
105
  }
84
106
  return values;
85
107
  },
86
108
  async mset(arguments_, ttl) {
87
- await Promise.all(caches.map(async (cache) => cache.store.mset(arguments_, ttl))).catch(error => eventEmitter.emit('error', error));
109
+ await Promise.all(caches.map(async (cache) => cache.store.mset(arguments_, ttl))).catch(error => {
110
+ const keys = arguments_.map(([key]) => key);
111
+ const data = arguments_.map(([, value]) => value);
112
+ const errorEvent = {
113
+ error, keys, data, operation: 'mset',
114
+ };
115
+ eventEmitter.emit('error', errorEvent);
116
+ });
88
117
  },
89
118
  async mdel(...keys) {
90
119
  await Promise.all(caches.map(async (cache) => cache.store.mdel(...keys)))
91
- .catch(error => eventEmitter.emit('error', error));
120
+ .catch(error => {
121
+ const errorEvent = { error, keys, operation: 'mdel' };
122
+ eventEmitter.emit('error', errorEvent);
123
+ });
92
124
  },
93
125
  on: (event, handler) => eventEmitter.on('error', handler),
126
+ removeListener: (event, handler) => eventEmitter.removeListener(event, handler),
94
127
  };
95
128
  }
96
129
  exports.multiCaching = multiCaching;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cache-manager",
3
- "version": "5.5.1",
3
+ "version": "5.5.3",
4
4
  "description": "Cache module for Node.js",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -36,20 +36,20 @@
36
36
  "dependencies": {
37
37
  "eventemitter3": "^5.0.1",
38
38
  "lodash.clonedeep": "^4.5.0",
39
- "lru-cache": "^10.2.0",
39
+ "lru-cache": "^10.2.2",
40
40
  "promise-coalesce": "^1.1.2"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@faker-js/faker": "^8.4.1",
44
44
  "@types/lodash.clonedeep": "^4.5.9",
45
- "@types/node": "^20.11.30",
46
- "@typescript-eslint/eslint-plugin": "^7.4.0",
47
- "@typescript-eslint/parser": "^7.4.0",
48
- "@vitest/coverage-v8": "^1.4.0",
45
+ "@types/node": "^20.12.7",
46
+ "@typescript-eslint/eslint-plugin": "^7.7.1",
47
+ "@typescript-eslint/parser": "^7.7.1",
48
+ "@vitest/coverage-v8": "^1.5.2",
49
49
  "eslint-config-xo-typescript": "^4.0.0",
50
50
  "rimraf": "^5.0.5",
51
- "typescript": "^5.4.3",
52
- "vitest": "^1.4.0",
51
+ "typescript": "^5.4.5",
52
+ "vitest": "^1.5.2",
53
53
  "xo": "^0.58.0"
54
54
  },
55
55
  "xo": {
@@ -60,9 +60,9 @@
60
60
  ]
61
61
  },
62
62
  "scripts": {
63
- "build": "rimraf dist && tsc -p tsconfig.build.json",
63
+ "build": "rimraf ./dist && tsc -p tsconfig.build.json",
64
64
  "clean": "rimraf ./dist ./coverage ./node_modules ./package-lock.json ./yarn.lock ./pnpm-lock.yaml",
65
65
  "test": "xo --fix && vitest run --coverage",
66
- "test:ci": "xo --fix && vitest run"
66
+ "test:ci": "xo && vitest run"
67
67
  }
68
68
  }