@cacheable/node-cache 2.0.2 → 3.0.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
@@ -22,11 +22,12 @@
22
22
  # Table of Contents
23
23
  * [Getting Started](#getting-started)
24
24
  * [Basic Usage](#basic-usage)
25
- * [Breaking Changes from v1 to v2](#breaking-changes-from-v1-to-v2)
26
25
  * [NodeCache Performance](#nodecache-performance)
27
26
  * [NodeCache API](#nodecache-api)
28
27
  * [NodeCacheStore](#nodecachestore)
29
28
  * [NodeCacheStore API](#nodecachestore-api)
29
+ * [Migrating to v2](#migrating-to-v2)
30
+ * [Migrating to v3](#migrating-to-v3)
30
31
  * [How to Contribute](#how-to-contribute)
31
32
  * [License and Copyright](#license-and-copyright)
32
33
 
@@ -47,7 +48,7 @@ cache.get('foo'); // 'bar'
47
48
 
48
49
  cache.set('foo', 'bar', 10); // 10 seconds
49
50
 
50
- cache.del('foo'); // true
51
+ cache.del('foo'); // 1
51
52
 
52
53
  cache.set('bar', 'baz', '35m'); // 35 minutes using shorthand
53
54
  ```
@@ -72,34 +73,6 @@ cache.set('foo', 'bar');
72
73
  cache.get('foo'); // 'bar'
73
74
  ```
74
75
 
75
- # Breaking Changes from v1 to v2
76
-
77
- The main `NodeCache` class API has not changed and remains fully compatible. The primary internal change is that it now uses Keyv as the underlying store.
78
-
79
- ## NodeCacheStore Changes
80
-
81
- ### Removed `cache` Property
82
- - **V1**: `nodeCache.cache` returned a `Cacheable` instance
83
- - **V2**: Use `nodeCache.store` which returns a `Keyv` instance
84
-
85
- ### Removed Storage Tiering (primary/secondary)
86
- - **V1**: Supported `primary` and `secondary` store options for multi-tier caching
87
- - **V2**: Uses single `store` option only
88
-
89
- **Migration:**
90
- ```javascript
91
- // V1
92
- const cache = new NodeCacheStore({ primary: keyv1, secondary: keyv2 });
93
-
94
- // V2 - use single store
95
- const cache = new NodeCacheStore({ store: keyv });
96
- ```
97
-
98
- If you need storage tiering functionality, use the `cacheable` package instead which supports primary and secondary stores.
99
-
100
- ### Internal Dependency Change
101
- - V2 uses `@cacheable/utils` instead of the `cacheable` package for a lighter footprint
102
-
103
76
  # NodeCache Performance
104
77
 
105
78
  The performance is comparable if not faster to the original `node-cache` package, but with additional features and improvements.
@@ -117,7 +90,7 @@ Create a new cache instance. You can pass in options to set the configuration:
117
90
 
118
91
  ```javascript
119
92
  export type NodeCacheOptions = {
120
- stdTTL?: number;
93
+ stdTTL?: number | string;
121
94
  checkperiod?: number;
122
95
  useClones?: boolean;
123
96
  deleteOnExpire?: boolean;
@@ -150,7 +123,7 @@ cache.on('expired', (key, value) => {
150
123
  });
151
124
  ```
152
125
 
153
- ## `set(key: string | number, value: any, ttl?: number): boolean`
126
+ ## `set(key: string | number, value: any, ttl?: number | string): boolean`
154
127
 
155
128
  Set a key value pair with an optional ttl (in seconds). Will return true on success. If the ttl is not set it will default to 0 (no ttl).
156
129
 
@@ -158,7 +131,7 @@ Set a key value pair with an optional ttl (in seconds). Will return true on succ
158
131
  cache.set('foo', 'bar', 10); // true
159
132
  ```
160
133
 
161
- ## `mset(data: Array<NodeCacheItem>): boolean`
134
+ ## `mset(data: Array<PartialNodeCacheItem>): boolean`
162
135
 
163
136
  Set multiple key value pairs at once. This will take an array of objects with the key, value, and optional ttl.
164
137
 
@@ -166,11 +139,11 @@ Set multiple key value pairs at once. This will take an array of objects with th
166
139
  cache.mset([{key: 'foo', value: 'bar', ttl: 10}, {key: 'bar', value: 'baz'}]); // true
167
140
  ```
168
141
 
169
- the `NodeCacheItem` is defined as:
142
+ the `PartialNodeCacheItem` is defined as:
170
143
 
171
144
  ```javascript
172
- export type NodeCacheItem = {
173
- key: string;
145
+ export type PartialNodeCacheItem = {
146
+ key: string | number;
174
147
  value: any;
175
148
  ttl?: number;
176
149
  };
@@ -211,13 +184,13 @@ cache.get('foo'); // undefined
211
184
  Delete a key from the cache. Will return the number of deleted entries and never fail. You can also pass in an array of keys to delete multiple keys. All examples assume that you have initialized the cache like `const cache = new NodeCache();`.
212
185
 
213
186
  ```javascript
214
- cache.del('foo'); // true
187
+ cache.del('foo'); // 1
215
188
  ```
216
189
 
217
190
  passing in an array of keys:
218
191
 
219
192
  ```javascript
220
- cache.del(['foo', 'bar']); // true
193
+ cache.del(['foo', 'bar']); // 2
221
194
  ```
222
195
 
223
196
  ## `mdel(keys: Array<string | number>): number`
@@ -225,10 +198,10 @@ cache.del(['foo', 'bar']); // true
225
198
  Delete multiple keys from the cache. Will return the number of deleted entries and never fail.
226
199
 
227
200
  ```javascript
228
- cache.mdel(['foo', 'bar']); // true
201
+ cache.mdel(['foo', 'bar']); // 2
229
202
  ```
230
203
 
231
- ## `ttl(key: string | number, ttl?: number): boolean`
204
+ ## `ttl(key: string | number, ttl?: number | string): boolean`
232
205
 
233
206
  Redefine the ttl of a key. Returns true if the key has been found and changed. Otherwise returns false. If the ttl-argument isn't passed the default-TTL will be used.
234
207
 
@@ -258,7 +231,7 @@ cache.has('foo'); // true
258
231
  Get all keys from the cache.
259
232
 
260
233
  ```javascript
261
- await cache.keys(); // ['foo', 'bar']
234
+ cache.keys(); // ['foo', 'bar']
262
235
  ```
263
236
 
264
237
  ## `getStats(): NodeCacheStats`
@@ -275,7 +248,7 @@ Flush the cache. Will remove all keys and reset the stats.
275
248
 
276
249
  ```javascript
277
250
  cache.flushAll();
278
- await cache.keys(); // []
251
+ cache.keys(); // []
279
252
  cache.getStats(); // {hits: 0, misses: 0, keys: 0, ksize: 0, vsize: 0}
280
253
  ```
281
254
 
@@ -284,10 +257,10 @@ cache.getStats(); // {hits: 0, misses: 0, keys: 0, ksize: 0, vsize: 0}
284
257
  Flush the stats. Will reset the stats but keep the keys.
285
258
 
286
259
  ```javascript
287
- await cache.set('foo', 'bar');
260
+ cache.set('foo', 'bar');
288
261
  cache.flushStats();
289
262
  cache.getStats(); // {hits: 0, misses: 0, keys: 0, ksize: 0, vsize: 0}
290
- await cache.keys(); // ['foo']
263
+ cache.keys(); // ['foo']
291
264
  ```
292
265
 
293
266
  ## `on(event: string, callback: Function): void`
@@ -305,6 +278,30 @@ cache.on('set', (key, value) => {
305
278
  });
306
279
  ```
307
280
 
281
+ ## `close(): void`
282
+
283
+ Close the cache. This will stop the interval timeout which is set on the `checkperiod` option.
284
+
285
+ ```javascript
286
+ cache.close();
287
+ ```
288
+
289
+ ## `store: Map<string, NodeCacheItem<T>>`
290
+
291
+ The internal store is a public readonly `Map` that holds all cached items. Each item includes the key, value, and TTL expiration timestamp.
292
+
293
+ ## `getIntervalId(): number | NodeJS.Timeout`
294
+
295
+ Get the interval ID for the expiration checker.
296
+
297
+ ## `startInterval(): void`
298
+
299
+ Start the interval for checking expired keys based on the `checkperiod` option.
300
+
301
+ ## `stopInterval(): void`
302
+
303
+ Stop the interval for checking expired keys.
304
+
308
305
  # NodeCacheStore
309
306
 
310
307
  `NodeCacheStore` has a similar API to `NodeCache` but it is using `async / await` as it uses [Keyv](https://keyv.org) under the hood. This means that you can use any storage adapter that is available in `Keyv` and it will work seamlessly with the `NodeCacheStore`. To learn more about the `Keyv` storage adapters you can check out the [Keyv documentation](https://keyv.org).
@@ -338,8 +335,6 @@ When initializing the cache you can pass in the options below:
338
335
  export type NodeCacheStoreOptions = {
339
336
  ttl?: number | string; // The standard ttl as number in milliseconds for every generated cache element. 0 = unlimited. Supports shorthand like '1h' for 1 hour.
340
337
  store?: Keyv; // The storage adapter (defaults to in-memory Keyv)
341
- maxKeys?: number; // Default is 0 (unlimited). If this is set it will return false when trying to set more keys than the max.
342
- stats?: boolean; // Default is true, if this is set to false it will not track stats internally
343
338
  };
344
339
  ```
345
340
 
@@ -353,19 +348,82 @@ await cache.set('longfoo', 'bar', '1d'); // 1 day
353
348
 
354
349
  ## NodeCacheStore API
355
350
 
356
- * `set(key: string | number, value: any, ttl?: number | string): Promise<boolean>` - Set a key value pair with an optional ttl (in milliseconds or shorthand string). Will return true on success, false if maxKeys limit is reached. If the ttl is not set it will default to the instance ttl or no expiration.
357
- * `mset(data: Array<NodeCacheItem>): Promise<void>` - Set multiple key value pairs at once
351
+ * `set(key: string | number, value: any, ttl?: number | string): Promise<boolean>` - Set a key value pair with an optional ttl (in milliseconds or shorthand string). Will return true on success. If the ttl is not set it will default to the instance ttl or no expiration.
352
+ * `mset(data: Array<PartialNodeCacheItem>): Promise<void>` - Set multiple key value pairs at once
358
353
  * `get<T>(key: string | number): Promise<T | undefined>` - Get a value from the cache by key
359
354
  * `mget<T>(keys: Array<string | number>): Promise<Record<string, T | undefined>>` - Get multiple values from the cache by keys
360
355
  * `take<T>(key: string | number): Promise<T | undefined>` - Get a value from the cache by key and delete it
361
356
  * `del(key: string | number): Promise<boolean>` - Delete a key
362
357
  * `mdel(keys: Array<string | number>): Promise<boolean>` - Delete multiple keys
363
358
  * `clear(): Promise<void>` - Clear the cache
364
- * `setTtl(key: string | number, ttl?: number): Promise<boolean>` - Set the ttl of an existing key
359
+ * `setTtl(key: string | number, ttl?: number | string): Promise<boolean>` - Set the ttl of an existing key
365
360
  * `disconnect(): Promise<void>` - Disconnect the storage adapter
366
361
  * `ttl`: `number | string | undefined` - The standard ttl for every generated cache element. `undefined` = unlimited
367
362
  * `store`: `Keyv` - The storage adapter (read-only)
368
- * `maxKeys`: `number` - If this is set it will return false when trying to set more keys than the max
363
+
364
+
365
+ # Migrating to v2
366
+
367
+ The main `NodeCache` class API has not changed and remains fully compatible. The primary internal change is that it now uses Keyv as the underlying store.
368
+
369
+ ## NodeCacheStore Changes
370
+
371
+ ### Removed `cache` Property
372
+ - **V1**: `nodeCache.cache` returned a `Cacheable` instance
373
+ - **V2**: Use `nodeCache.store` which returns a `Keyv` instance
374
+
375
+ ### Removed Storage Tiering (primary/secondary)
376
+ - **V1**: Supported `primary` and `secondary` store options for multi-tier caching
377
+ - **V2**: Uses single `store` option only
378
+
379
+ **Migration:**
380
+ ```javascript
381
+ // V1
382
+ const cache = new NodeCacheStore({ primary: keyv1, secondary: keyv2 });
383
+
384
+ // V2 - use single store
385
+ const cache = new NodeCacheStore({ store: keyv });
386
+ ```
387
+
388
+ If you need storage tiering functionality, use the `cacheable` package instead which supports primary and secondary stores.
389
+
390
+ ### Internal Dependency Change
391
+ - V2 uses `@cacheable/utils` instead of the `cacheable` package for a lighter footprint
392
+
393
+ # Migrating to v3
394
+
395
+ ## Removed `maxKeys` from NodeCacheStore
396
+
397
+ The `maxKeys` option has been removed from `NodeCacheStore`. It does not make sense for a store backed by external services (Redis, MongoDB, etc.) where the backend manages its own capacity.
398
+
399
+ The `maxKeys` option remains available on the in-memory `NodeCache` class.
400
+
401
+ **Migration:**
402
+ ```javascript
403
+ // V2 - maxKeys was accepted but not meaningful for external stores
404
+ const cache = new NodeCacheStore({ maxKeys: 100 });
405
+
406
+ // V3 - remove maxKeys from NodeCacheStore options
407
+ const cache = new NodeCacheStore();
408
+ ```
409
+
410
+ If you need key limits with an external store, configure the limit at the storage layer instead.
411
+
412
+ ## Removed `stats` from NodeCacheStore
413
+
414
+ The `stats` option and internal stats tracking have been removed from `NodeCacheStore`. The stats were collected internally but never exposed via a public API, making them effectively unused.
415
+
416
+ ## Upgraded `hookified` to v2
417
+
418
+ The underlying `hookified` dependency has been upgraded from v1 to v2. Both `NodeCache` and `NodeCacheStore` extend `Hookified`. Key changes in hookified v2:
419
+
420
+ - `logger` property renamed to `eventLogger`
421
+ - `Hook` type renamed to `HookFn`
422
+ - `onHook` signature changed to handle `IHook` interface
423
+ - Removed `throwHookErrors` configuration option
424
+ - `throwOnEmptyListeners` default changed to `true`
425
+
426
+ If you use hooks or advanced event features from the `Hookified` base class directly, review the [hookified v2 changelog](https://github.com/jaredwray/hookified) for details.
369
427
 
370
428
  # How to Contribute
371
429
 
package/dist/index.cjs CHANGED
@@ -44,18 +44,13 @@ var import_utils = require("@cacheable/utils");
44
44
  var import_hookified = require("hookified");
45
45
  var import_keyv = __toESM(require("keyv"), 1);
46
46
  var NodeCacheStore = class extends import_hookified.Hookified {
47
- _maxKeys = 0;
48
47
  _keyv;
49
- _stats;
50
48
  _ttl;
49
+ _stats = new import_utils.Stats({ enabled: true });
51
50
  constructor(options) {
52
51
  super();
53
- this._stats = new import_utils.Stats({ enabled: options?.stats ?? true });
54
52
  this._ttl = options?.ttl;
55
53
  this._keyv = options?.store ?? new import_keyv.default();
56
- if (options?.maxKeys) {
57
- this._maxKeys = options.maxKeys;
58
- }
59
54
  this._keyv.on("error", (error) => {
60
55
  this.emit("error", error);
61
56
  });
@@ -83,26 +78,6 @@ var NodeCacheStore = class extends import_hookified.Hookified {
83
78
  get store() {
84
79
  return this._keyv;
85
80
  }
86
- /**
87
- * Maximum number of keys to store in the cache. if this is set to a value greater than 0,
88
- * the cache will keep track of the number of keys and will not store more than the specified number of keys.
89
- * @returns {number}
90
- * @readonly
91
- */
92
- get maxKeys() {
93
- return this._maxKeys;
94
- }
95
- /**
96
- * Maximum number of keys to store in the cache. if this is set to a value greater than 0,
97
- * the cache will keep track of the number of keys and will not store more than the specified number of keys.
98
- * @param {number} maxKeys
99
- */
100
- set maxKeys(maxKeys) {
101
- this._maxKeys = maxKeys;
102
- if (this._maxKeys > 0) {
103
- this._stats.enabled = true;
104
- }
105
- }
106
81
  /**
107
82
  * Set a key/value pair in the cache.
108
83
  * @param {string | number} key
@@ -111,13 +86,11 @@ var NodeCacheStore = class extends import_hookified.Hookified {
111
86
  * @returns {boolean}
112
87
  */
113
88
  async set(key, value, ttl) {
114
- if (this._maxKeys > 0) {
115
- if (this._stats.count >= this._maxKeys) {
116
- return false;
117
- }
118
- }
89
+ const keyValue = key.toString();
119
90
  const finalTtl = this.resolveTtl(ttl);
120
- await this._keyv.set(key.toString(), value, finalTtl);
91
+ await this._keyv.set(keyValue, value, finalTtl);
92
+ this._stats.incrementKSize(keyValue);
93
+ this._stats.incrementVSize(value);
121
94
  this._stats.incrementCount();
122
95
  return true;
123
96
  }
@@ -128,8 +101,11 @@ var NodeCacheStore = class extends import_hookified.Hookified {
128
101
  */
129
102
  async mset(list) {
130
103
  for (const item of list) {
104
+ const keyValue = item.key.toString();
131
105
  const finalTtl = this.resolveTtl(item.ttl);
132
- await this._keyv.set(item.key.toString(), item.value, finalTtl);
106
+ await this._keyv.set(keyValue, item.value, finalTtl);
107
+ this._stats.incrementKSize(keyValue);
108
+ this._stats.incrementVSize(item.value);
133
109
  this._stats.incrementCount();
134
110
  }
135
111
  }
@@ -140,10 +116,10 @@ var NodeCacheStore = class extends import_hookified.Hookified {
140
116
  */
141
117
  async get(key) {
142
118
  const result = await this._keyv.get(key.toString());
143
- if (result !== void 0) {
144
- this._stats.incrementHits();
145
- } else {
119
+ if (result === void 0) {
146
120
  this._stats.incrementMisses();
121
+ } else {
122
+ this._stats.incrementHits();
147
123
  }
148
124
  return result;
149
125
  }
@@ -153,13 +129,13 @@ var NodeCacheStore = class extends import_hookified.Hookified {
153
129
  * @returns {Record<string, any | undefined>}
154
130
  */
155
131
  async mget(keys) {
156
- const result = {};
132
+ const result = /* @__PURE__ */ Object.create(null);
157
133
  for (const key of keys) {
158
134
  const value = await this._keyv.get(key.toString());
159
- if (value !== void 0) {
160
- this._stats.incrementHits();
161
- } else {
135
+ if (value === void 0) {
162
136
  this._stats.incrementMisses();
137
+ } else {
138
+ this._stats.incrementHits();
163
139
  }
164
140
  result[key.toString()] = value;
165
141
  }
@@ -171,11 +147,17 @@ var NodeCacheStore = class extends import_hookified.Hookified {
171
147
  * @returns {boolean}
172
148
  */
173
149
  async del(key) {
174
- const deleted = await this._keyv.delete(key.toString());
175
- if (deleted) {
150
+ const keyValue = key.toString();
151
+ const value = await this._keyv.get(keyValue);
152
+ const result = await this._keyv.delete(keyValue);
153
+ if (result) {
154
+ this._stats.decreaseKSize(keyValue);
155
+ if (value !== void 0) {
156
+ this._stats.decreaseVSize(value);
157
+ }
176
158
  this._stats.decreaseCount();
177
159
  }
178
- return deleted;
160
+ return result;
179
161
  }
180
162
  /**
181
163
  * Delete multiple keys from the cache.
@@ -183,13 +165,16 @@ var NodeCacheStore = class extends import_hookified.Hookified {
183
165
  * @returns {boolean}
184
166
  */
185
167
  async mdel(keys) {
186
- const deleted = await this._keyv.delete(keys.map((key) => key.toString()));
187
- if (deleted) {
188
- for (const _ of keys) {
189
- this._stats.decreaseCount();
168
+ for (const key of keys) {
169
+ const keyValue = key.toString();
170
+ const value = await this._keyv.get(keyValue);
171
+ this._stats.decreaseKSize(keyValue);
172
+ if (value !== void 0) {
173
+ this._stats.decreaseVSize(value);
190
174
  }
175
+ this._stats.decreaseCount();
191
176
  }
192
- return deleted;
177
+ return this._keyv.delete(keys.map((key) => key.toString()));
193
178
  }
194
179
  /**
195
180
  * Clear the cache.
@@ -220,16 +205,40 @@ var NodeCacheStore = class extends import_hookified.Hookified {
220
205
  * @returns {T | undefined}
221
206
  */
222
207
  async take(key) {
223
- const result = await this._keyv.get(key.toString());
208
+ const keyValue = key.toString();
209
+ const result = await this._keyv.get(keyValue);
224
210
  if (result !== void 0) {
211
+ await this._keyv.delete(keyValue);
225
212
  this._stats.incrementHits();
226
- await this._keyv.delete(key.toString());
213
+ this._stats.decreaseKSize(keyValue);
214
+ this._stats.decreaseVSize(result);
227
215
  this._stats.decreaseCount();
228
216
  } else {
229
217
  this._stats.incrementMisses();
230
218
  }
231
219
  return result;
232
220
  }
221
+ /**
222
+ * Gets the stats of the cache
223
+ * @returns {NodeCacheStats} the stats of the cache
224
+ */
225
+ getStats() {
226
+ return {
227
+ keys: this._stats.count,
228
+ hits: this._stats.hits,
229
+ misses: this._stats.misses,
230
+ ksize: this._stats.ksize,
231
+ vsize: this._stats.vsize
232
+ };
233
+ }
234
+ /**
235
+ * Flush the stats.
236
+ * @returns {void}
237
+ */
238
+ flushStats() {
239
+ this._stats = new import_utils.Stats({ enabled: true });
240
+ this.emit("flush_stats");
241
+ }
233
242
  /**
234
243
  * Disconnect from the cache.
235
244
  * @returns {void}
@@ -277,7 +286,7 @@ var NodeCache = class extends import_hookified2.Hookified {
277
286
  _stats = new import_utils2.Stats({ enabled: true });
278
287
  intervalId = 0;
279
288
  constructor(options) {
280
- super();
289
+ super({ throwOnHookError: false });
281
290
  if (options) {
282
291
  this.options = { ...this.options, ...options };
283
292
  }
@@ -369,11 +378,8 @@ var NodeCache = class extends import_hookified2.Hookified {
369
378
  if (result) {
370
379
  if (result.ttl > 0) {
371
380
  if (result.ttl < Date.now()) {
372
- if (this.options.deleteOnExpire) {
373
- this.del(key);
374
- }
375
381
  this._stats.incrementMisses();
376
- this.emit("expired", this.formatKey(key), result.value);
382
+ this.handleExpired(key, result);
377
383
  return void 0;
378
384
  }
379
385
  this._stats.incrementHits();
@@ -398,7 +404,7 @@ var NodeCache = class extends import_hookified2.Hookified {
398
404
  * @returns {Record<string, T | undefined>} an object with the key as a property and the value as the value
399
405
  */
400
406
  mget(keys) {
401
- const result = {};
407
+ const result = /* @__PURE__ */ Object.create(null);
402
408
  for (const key of keys) {
403
409
  const value = this.get(key);
404
410
  if (value) {
@@ -528,12 +534,22 @@ var NodeCache = class extends import_hookified2.Hookified {
528
534
  return result;
529
535
  }
530
536
  /**
531
- * Returns boolean indicating if the key is cached.
537
+ * Returns boolean indicating if the key is cached. If the key has expired, it
538
+ * will return false and the key will be removed from the cache when
539
+ * `deleteOnExpire` is enabled (matches the original node-cache behavior).
532
540
  * @param {string | number} key if the key is a number it will convert it to a string
533
- * @returns {boolean} true if the key is cached
541
+ * @returns {boolean} true if the key is cached and not expired
534
542
  */
535
543
  has(key) {
536
- return this.store.has(this.formatKey(key));
544
+ const result = this.store.get(this.formatKey(key));
545
+ if (!result) {
546
+ return false;
547
+ }
548
+ if (result.ttl > 0 && result.ttl < Date.now()) {
549
+ this.handleExpired(key, result);
550
+ return false;
551
+ }
552
+ return true;
537
553
  }
538
554
  /**
539
555
  * Gets the stats of the cache
@@ -648,13 +664,21 @@ var NodeCache = class extends import_hookified2.Hookified {
648
664
  checkData() {
649
665
  for (const [key, value] of this.store.entries()) {
650
666
  if (value.ttl > 0 && value.ttl < Date.now()) {
651
- if (this.options.deleteOnExpire) {
652
- this.del(key);
653
- }
654
- this.emit("expired", this.formatKey(key), value.value);
667
+ this.handleExpired(key, value);
655
668
  }
656
669
  }
657
670
  }
671
+ /**
672
+ * Handles expiration for a cache entry. Deletes the entry when
673
+ * `deleteOnExpire` is enabled and emits the "expired" event.
674
+ */
675
+ handleExpired(key, entry) {
676
+ const keyValue = this.formatKey(key);
677
+ if (this.options.deleteOnExpire) {
678
+ this.del(key);
679
+ }
680
+ this.emit("expired", keyValue, entry.value);
681
+ }
658
682
  createError(errorCode, key) {
659
683
  let error = errorCode;
660
684
  if (key) {
package/dist/index.d.cts CHANGED
@@ -6,24 +6,15 @@ type NodeCacheStoreOptions<T> = {
6
6
  * Time to live in milliseconds. This is a breaking change from the original NodeCache.
7
7
  */
8
8
  ttl?: number | string;
9
- /**
10
- * Maximum number of keys to store in the cache. If this is set to a value greater than 0, the cache will keep track of the number of keys and will not store more than the specified number of keys.
11
- */
12
- maxKeys?: number;
13
9
  /**
14
10
  * The Keyv store instance.
15
11
  */
16
12
  store?: Keyv<T>;
17
- /**
18
- * Enable stats tracking. This is a breaking change from the original NodeCache.
19
- */
20
- stats?: boolean;
21
13
  };
22
14
  declare class NodeCacheStore<T> extends Hookified {
23
- private _maxKeys;
24
15
  private _keyv;
25
- private readonly _stats;
26
16
  private _ttl?;
17
+ private _stats;
27
18
  constructor(options?: NodeCacheStoreOptions<T>);
28
19
  /**
29
20
  * Time to live in milliseconds.
@@ -42,19 +33,6 @@ declare class NodeCacheStore<T> extends Hookified {
42
33
  * @readonly
43
34
  */
44
35
  get store(): Keyv<T>;
45
- /**
46
- * Maximum number of keys to store in the cache. if this is set to a value greater than 0,
47
- * the cache will keep track of the number of keys and will not store more than the specified number of keys.
48
- * @returns {number}
49
- * @readonly
50
- */
51
- get maxKeys(): number;
52
- /**
53
- * Maximum number of keys to store in the cache. if this is set to a value greater than 0,
54
- * the cache will keep track of the number of keys and will not store more than the specified number of keys.
55
- * @param {number} maxKeys
56
- */
57
- set maxKeys(maxKeys: number);
58
36
  /**
59
37
  * Set a key/value pair in the cache.
60
38
  * @param {string | number} key
@@ -74,13 +52,13 @@ declare class NodeCacheStore<T> extends Hookified {
74
52
  * @param {string | number} key
75
53
  * @returns {any | undefined}
76
54
  */
77
- get<T>(key: string | number): Promise<T | undefined>;
55
+ get<V = T>(key: string | number): Promise<V | undefined>;
78
56
  /**
79
57
  * Get multiple values from the cache.
80
58
  * @param {Array<string | number>} keys
81
59
  * @returns {Record<string, any | undefined>}
82
60
  */
83
- mget<T>(keys: Array<string | number>): Promise<Record<string, T | undefined>>;
61
+ mget<V = T>(keys: Array<string | number>): Promise<Record<string, V | undefined>>;
84
62
  /**
85
63
  * Delete a key from the cache.
86
64
  * @param {string | number} key
@@ -110,7 +88,17 @@ declare class NodeCacheStore<T> extends Hookified {
110
88
  * @param {string | number} key
111
89
  * @returns {T | undefined}
112
90
  */
113
- take<T>(key: string | number): Promise<T | undefined>;
91
+ take<V = T>(key: string | number): Promise<V | undefined>;
92
+ /**
93
+ * Gets the stats of the cache
94
+ * @returns {NodeCacheStats} the stats of the cache
95
+ */
96
+ getStats(): NodeCacheStats;
97
+ /**
98
+ * Flush the stats.
99
+ * @returns {void}
100
+ */
101
+ flushStats(): void;
114
102
  /**
115
103
  * Disconnect from the cache.
116
104
  * @returns {void}
@@ -249,14 +237,14 @@ declare class NodeCache<T> extends Hookified {
249
237
  * @param {Array<string | number} keys an array of keys
250
238
  * @returns {Record<string, T | undefined>} an object with the key as a property and the value as the value
251
239
  */
252
- mget<T>(keys: Array<string | number>): Record<string, T | undefined>;
240
+ mget<V = T>(keys: Array<string | number>): Record<string, V | undefined>;
253
241
  /**
254
242
  * Get the cached value and remove the key from the cache. Equivalent to calling get(key) + del(key).
255
243
  * Useful for implementing single use mechanism such as OTP, where once a value is read it will become obsolete.
256
244
  * @param {string | number} key
257
245
  * @returns {T | undefined} the value or undefined
258
246
  */
259
- take<T>(key: string | number): T | undefined;
247
+ take<V = T>(key: string | number): V | undefined;
260
248
  /**
261
249
  * Delete a key. Returns the number of deleted entries. A delete will never fail.
262
250
  * @param {string | number | Array<string | number>} key if the key is a number it will convert it to a string. if an array is passed it will delete all keys in the array.
@@ -299,9 +287,11 @@ declare class NodeCache<T> extends Hookified {
299
287
  */
300
288
  keys(): string[];
301
289
  /**
302
- * Returns boolean indicating if the key is cached.
290
+ * Returns boolean indicating if the key is cached. If the key has expired, it
291
+ * will return false and the key will be removed from the cache when
292
+ * `deleteOnExpire` is enabled (matches the original node-cache behavior).
303
293
  * @param {string | number} key if the key is a number it will convert it to a string
304
- * @returns {boolean} true if the key is cached
294
+ * @returns {boolean} true if the key is cached and not expired
305
295
  */
306
296
  has(key: string | number): boolean;
307
297
  /**
@@ -345,6 +335,11 @@ declare class NodeCache<T> extends Hookified {
345
335
  */
346
336
  private isNegativeTtl;
347
337
  private checkData;
338
+ /**
339
+ * Handles expiration for a cache entry. Deletes the entry when
340
+ * `deleteOnExpire` is enabled and emits the "expired" event.
341
+ */
342
+ private handleExpired;
348
343
  private createError;
349
344
  }
350
345
 
package/dist/index.d.ts CHANGED
@@ -6,24 +6,15 @@ type NodeCacheStoreOptions<T> = {
6
6
  * Time to live in milliseconds. This is a breaking change from the original NodeCache.
7
7
  */
8
8
  ttl?: number | string;
9
- /**
10
- * Maximum number of keys to store in the cache. If this is set to a value greater than 0, the cache will keep track of the number of keys and will not store more than the specified number of keys.
11
- */
12
- maxKeys?: number;
13
9
  /**
14
10
  * The Keyv store instance.
15
11
  */
16
12
  store?: Keyv<T>;
17
- /**
18
- * Enable stats tracking. This is a breaking change from the original NodeCache.
19
- */
20
- stats?: boolean;
21
13
  };
22
14
  declare class NodeCacheStore<T> extends Hookified {
23
- private _maxKeys;
24
15
  private _keyv;
25
- private readonly _stats;
26
16
  private _ttl?;
17
+ private _stats;
27
18
  constructor(options?: NodeCacheStoreOptions<T>);
28
19
  /**
29
20
  * Time to live in milliseconds.
@@ -42,19 +33,6 @@ declare class NodeCacheStore<T> extends Hookified {
42
33
  * @readonly
43
34
  */
44
35
  get store(): Keyv<T>;
45
- /**
46
- * Maximum number of keys to store in the cache. if this is set to a value greater than 0,
47
- * the cache will keep track of the number of keys and will not store more than the specified number of keys.
48
- * @returns {number}
49
- * @readonly
50
- */
51
- get maxKeys(): number;
52
- /**
53
- * Maximum number of keys to store in the cache. if this is set to a value greater than 0,
54
- * the cache will keep track of the number of keys and will not store more than the specified number of keys.
55
- * @param {number} maxKeys
56
- */
57
- set maxKeys(maxKeys: number);
58
36
  /**
59
37
  * Set a key/value pair in the cache.
60
38
  * @param {string | number} key
@@ -74,13 +52,13 @@ declare class NodeCacheStore<T> extends Hookified {
74
52
  * @param {string | number} key
75
53
  * @returns {any | undefined}
76
54
  */
77
- get<T>(key: string | number): Promise<T | undefined>;
55
+ get<V = T>(key: string | number): Promise<V | undefined>;
78
56
  /**
79
57
  * Get multiple values from the cache.
80
58
  * @param {Array<string | number>} keys
81
59
  * @returns {Record<string, any | undefined>}
82
60
  */
83
- mget<T>(keys: Array<string | number>): Promise<Record<string, T | undefined>>;
61
+ mget<V = T>(keys: Array<string | number>): Promise<Record<string, V | undefined>>;
84
62
  /**
85
63
  * Delete a key from the cache.
86
64
  * @param {string | number} key
@@ -110,7 +88,17 @@ declare class NodeCacheStore<T> extends Hookified {
110
88
  * @param {string | number} key
111
89
  * @returns {T | undefined}
112
90
  */
113
- take<T>(key: string | number): Promise<T | undefined>;
91
+ take<V = T>(key: string | number): Promise<V | undefined>;
92
+ /**
93
+ * Gets the stats of the cache
94
+ * @returns {NodeCacheStats} the stats of the cache
95
+ */
96
+ getStats(): NodeCacheStats;
97
+ /**
98
+ * Flush the stats.
99
+ * @returns {void}
100
+ */
101
+ flushStats(): void;
114
102
  /**
115
103
  * Disconnect from the cache.
116
104
  * @returns {void}
@@ -249,14 +237,14 @@ declare class NodeCache<T> extends Hookified {
249
237
  * @param {Array<string | number} keys an array of keys
250
238
  * @returns {Record<string, T | undefined>} an object with the key as a property and the value as the value
251
239
  */
252
- mget<T>(keys: Array<string | number>): Record<string, T | undefined>;
240
+ mget<V = T>(keys: Array<string | number>): Record<string, V | undefined>;
253
241
  /**
254
242
  * Get the cached value and remove the key from the cache. Equivalent to calling get(key) + del(key).
255
243
  * Useful for implementing single use mechanism such as OTP, where once a value is read it will become obsolete.
256
244
  * @param {string | number} key
257
245
  * @returns {T | undefined} the value or undefined
258
246
  */
259
- take<T>(key: string | number): T | undefined;
247
+ take<V = T>(key: string | number): V | undefined;
260
248
  /**
261
249
  * Delete a key. Returns the number of deleted entries. A delete will never fail.
262
250
  * @param {string | number | Array<string | number>} key if the key is a number it will convert it to a string. if an array is passed it will delete all keys in the array.
@@ -299,9 +287,11 @@ declare class NodeCache<T> extends Hookified {
299
287
  */
300
288
  keys(): string[];
301
289
  /**
302
- * Returns boolean indicating if the key is cached.
290
+ * Returns boolean indicating if the key is cached. If the key has expired, it
291
+ * will return false and the key will be removed from the cache when
292
+ * `deleteOnExpire` is enabled (matches the original node-cache behavior).
303
293
  * @param {string | number} key if the key is a number it will convert it to a string
304
- * @returns {boolean} true if the key is cached
294
+ * @returns {boolean} true if the key is cached and not expired
305
295
  */
306
296
  has(key: string | number): boolean;
307
297
  /**
@@ -345,6 +335,11 @@ declare class NodeCache<T> extends Hookified {
345
335
  */
346
336
  private isNegativeTtl;
347
337
  private checkData;
338
+ /**
339
+ * Handles expiration for a cache entry. Deletes the entry when
340
+ * `deleteOnExpire` is enabled and emits the "expired" event.
341
+ */
342
+ private handleExpired;
348
343
  private createError;
349
344
  }
350
345
 
package/dist/index.js CHANGED
@@ -7,18 +7,13 @@ import { Stats, shorthandToMilliseconds } from "@cacheable/utils";
7
7
  import { Hookified } from "hookified";
8
8
  import Keyv from "keyv";
9
9
  var NodeCacheStore = class extends Hookified {
10
- _maxKeys = 0;
11
10
  _keyv;
12
- _stats;
13
11
  _ttl;
12
+ _stats = new Stats({ enabled: true });
14
13
  constructor(options) {
15
14
  super();
16
- this._stats = new Stats({ enabled: options?.stats ?? true });
17
15
  this._ttl = options?.ttl;
18
16
  this._keyv = options?.store ?? new Keyv();
19
- if (options?.maxKeys) {
20
- this._maxKeys = options.maxKeys;
21
- }
22
17
  this._keyv.on("error", (error) => {
23
18
  this.emit("error", error);
24
19
  });
@@ -46,26 +41,6 @@ var NodeCacheStore = class extends Hookified {
46
41
  get store() {
47
42
  return this._keyv;
48
43
  }
49
- /**
50
- * Maximum number of keys to store in the cache. if this is set to a value greater than 0,
51
- * the cache will keep track of the number of keys and will not store more than the specified number of keys.
52
- * @returns {number}
53
- * @readonly
54
- */
55
- get maxKeys() {
56
- return this._maxKeys;
57
- }
58
- /**
59
- * Maximum number of keys to store in the cache. if this is set to a value greater than 0,
60
- * the cache will keep track of the number of keys and will not store more than the specified number of keys.
61
- * @param {number} maxKeys
62
- */
63
- set maxKeys(maxKeys) {
64
- this._maxKeys = maxKeys;
65
- if (this._maxKeys > 0) {
66
- this._stats.enabled = true;
67
- }
68
- }
69
44
  /**
70
45
  * Set a key/value pair in the cache.
71
46
  * @param {string | number} key
@@ -74,13 +49,11 @@ var NodeCacheStore = class extends Hookified {
74
49
  * @returns {boolean}
75
50
  */
76
51
  async set(key, value, ttl) {
77
- if (this._maxKeys > 0) {
78
- if (this._stats.count >= this._maxKeys) {
79
- return false;
80
- }
81
- }
52
+ const keyValue = key.toString();
82
53
  const finalTtl = this.resolveTtl(ttl);
83
- await this._keyv.set(key.toString(), value, finalTtl);
54
+ await this._keyv.set(keyValue, value, finalTtl);
55
+ this._stats.incrementKSize(keyValue);
56
+ this._stats.incrementVSize(value);
84
57
  this._stats.incrementCount();
85
58
  return true;
86
59
  }
@@ -91,8 +64,11 @@ var NodeCacheStore = class extends Hookified {
91
64
  */
92
65
  async mset(list) {
93
66
  for (const item of list) {
67
+ const keyValue = item.key.toString();
94
68
  const finalTtl = this.resolveTtl(item.ttl);
95
- await this._keyv.set(item.key.toString(), item.value, finalTtl);
69
+ await this._keyv.set(keyValue, item.value, finalTtl);
70
+ this._stats.incrementKSize(keyValue);
71
+ this._stats.incrementVSize(item.value);
96
72
  this._stats.incrementCount();
97
73
  }
98
74
  }
@@ -103,10 +79,10 @@ var NodeCacheStore = class extends Hookified {
103
79
  */
104
80
  async get(key) {
105
81
  const result = await this._keyv.get(key.toString());
106
- if (result !== void 0) {
107
- this._stats.incrementHits();
108
- } else {
82
+ if (result === void 0) {
109
83
  this._stats.incrementMisses();
84
+ } else {
85
+ this._stats.incrementHits();
110
86
  }
111
87
  return result;
112
88
  }
@@ -116,13 +92,13 @@ var NodeCacheStore = class extends Hookified {
116
92
  * @returns {Record<string, any | undefined>}
117
93
  */
118
94
  async mget(keys) {
119
- const result = {};
95
+ const result = /* @__PURE__ */ Object.create(null);
120
96
  for (const key of keys) {
121
97
  const value = await this._keyv.get(key.toString());
122
- if (value !== void 0) {
123
- this._stats.incrementHits();
124
- } else {
98
+ if (value === void 0) {
125
99
  this._stats.incrementMisses();
100
+ } else {
101
+ this._stats.incrementHits();
126
102
  }
127
103
  result[key.toString()] = value;
128
104
  }
@@ -134,11 +110,17 @@ var NodeCacheStore = class extends Hookified {
134
110
  * @returns {boolean}
135
111
  */
136
112
  async del(key) {
137
- const deleted = await this._keyv.delete(key.toString());
138
- if (deleted) {
113
+ const keyValue = key.toString();
114
+ const value = await this._keyv.get(keyValue);
115
+ const result = await this._keyv.delete(keyValue);
116
+ if (result) {
117
+ this._stats.decreaseKSize(keyValue);
118
+ if (value !== void 0) {
119
+ this._stats.decreaseVSize(value);
120
+ }
139
121
  this._stats.decreaseCount();
140
122
  }
141
- return deleted;
123
+ return result;
142
124
  }
143
125
  /**
144
126
  * Delete multiple keys from the cache.
@@ -146,13 +128,16 @@ var NodeCacheStore = class extends Hookified {
146
128
  * @returns {boolean}
147
129
  */
148
130
  async mdel(keys) {
149
- const deleted = await this._keyv.delete(keys.map((key) => key.toString()));
150
- if (deleted) {
151
- for (const _ of keys) {
152
- this._stats.decreaseCount();
131
+ for (const key of keys) {
132
+ const keyValue = key.toString();
133
+ const value = await this._keyv.get(keyValue);
134
+ this._stats.decreaseKSize(keyValue);
135
+ if (value !== void 0) {
136
+ this._stats.decreaseVSize(value);
153
137
  }
138
+ this._stats.decreaseCount();
154
139
  }
155
- return deleted;
140
+ return this._keyv.delete(keys.map((key) => key.toString()));
156
141
  }
157
142
  /**
158
143
  * Clear the cache.
@@ -183,16 +168,40 @@ var NodeCacheStore = class extends Hookified {
183
168
  * @returns {T | undefined}
184
169
  */
185
170
  async take(key) {
186
- const result = await this._keyv.get(key.toString());
171
+ const keyValue = key.toString();
172
+ const result = await this._keyv.get(keyValue);
187
173
  if (result !== void 0) {
174
+ await this._keyv.delete(keyValue);
188
175
  this._stats.incrementHits();
189
- await this._keyv.delete(key.toString());
176
+ this._stats.decreaseKSize(keyValue);
177
+ this._stats.decreaseVSize(result);
190
178
  this._stats.decreaseCount();
191
179
  } else {
192
180
  this._stats.incrementMisses();
193
181
  }
194
182
  return result;
195
183
  }
184
+ /**
185
+ * Gets the stats of the cache
186
+ * @returns {NodeCacheStats} the stats of the cache
187
+ */
188
+ getStats() {
189
+ return {
190
+ keys: this._stats.count,
191
+ hits: this._stats.hits,
192
+ misses: this._stats.misses,
193
+ ksize: this._stats.ksize,
194
+ vsize: this._stats.vsize
195
+ };
196
+ }
197
+ /**
198
+ * Flush the stats.
199
+ * @returns {void}
200
+ */
201
+ flushStats() {
202
+ this._stats = new Stats({ enabled: true });
203
+ this.emit("flush_stats");
204
+ }
196
205
  /**
197
206
  * Disconnect from the cache.
198
207
  * @returns {void}
@@ -240,7 +249,7 @@ var NodeCache = class extends Hookified2 {
240
249
  _stats = new Stats2({ enabled: true });
241
250
  intervalId = 0;
242
251
  constructor(options) {
243
- super();
252
+ super({ throwOnHookError: false });
244
253
  if (options) {
245
254
  this.options = { ...this.options, ...options };
246
255
  }
@@ -332,11 +341,8 @@ var NodeCache = class extends Hookified2 {
332
341
  if (result) {
333
342
  if (result.ttl > 0) {
334
343
  if (result.ttl < Date.now()) {
335
- if (this.options.deleteOnExpire) {
336
- this.del(key);
337
- }
338
344
  this._stats.incrementMisses();
339
- this.emit("expired", this.formatKey(key), result.value);
345
+ this.handleExpired(key, result);
340
346
  return void 0;
341
347
  }
342
348
  this._stats.incrementHits();
@@ -361,7 +367,7 @@ var NodeCache = class extends Hookified2 {
361
367
  * @returns {Record<string, T | undefined>} an object with the key as a property and the value as the value
362
368
  */
363
369
  mget(keys) {
364
- const result = {};
370
+ const result = /* @__PURE__ */ Object.create(null);
365
371
  for (const key of keys) {
366
372
  const value = this.get(key);
367
373
  if (value) {
@@ -491,12 +497,22 @@ var NodeCache = class extends Hookified2 {
491
497
  return result;
492
498
  }
493
499
  /**
494
- * Returns boolean indicating if the key is cached.
500
+ * Returns boolean indicating if the key is cached. If the key has expired, it
501
+ * will return false and the key will be removed from the cache when
502
+ * `deleteOnExpire` is enabled (matches the original node-cache behavior).
495
503
  * @param {string | number} key if the key is a number it will convert it to a string
496
- * @returns {boolean} true if the key is cached
504
+ * @returns {boolean} true if the key is cached and not expired
497
505
  */
498
506
  has(key) {
499
- return this.store.has(this.formatKey(key));
507
+ const result = this.store.get(this.formatKey(key));
508
+ if (!result) {
509
+ return false;
510
+ }
511
+ if (result.ttl > 0 && result.ttl < Date.now()) {
512
+ this.handleExpired(key, result);
513
+ return false;
514
+ }
515
+ return true;
500
516
  }
501
517
  /**
502
518
  * Gets the stats of the cache
@@ -611,13 +627,21 @@ var NodeCache = class extends Hookified2 {
611
627
  checkData() {
612
628
  for (const [key, value] of this.store.entries()) {
613
629
  if (value.ttl > 0 && value.ttl < Date.now()) {
614
- if (this.options.deleteOnExpire) {
615
- this.del(key);
616
- }
617
- this.emit("expired", this.formatKey(key), value.value);
630
+ this.handleExpired(key, value);
618
631
  }
619
632
  }
620
633
  }
634
+ /**
635
+ * Handles expiration for a cache entry. Deletes the entry when
636
+ * `deleteOnExpire` is enabled and emits the "expired" event.
637
+ */
638
+ handleExpired(key, entry) {
639
+ const keyValue = this.formatKey(key);
640
+ if (this.options.deleteOnExpire) {
641
+ this.del(key);
642
+ }
643
+ this.emit("expired", keyValue, entry.value);
644
+ }
621
645
  createError(errorCode, key) {
622
646
  let error = errorCode;
623
647
  if (key) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cacheable/node-cache",
3
- "version": "2.0.2",
3
+ "version": "3.0.1",
4
4
  "description": "Simple and Maintained fast NodeJS internal caching",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -40,16 +40,13 @@
40
40
  "cacheable-node"
41
41
  ],
42
42
  "devDependencies": {
43
- "@faker-js/faker": "^10.2.0",
44
- "@types/node": "^24.10.10",
45
- "rimraf": "^6.1.2",
46
43
  "tsup": "^8.5.1",
47
44
  "typescript": "^5.9.3"
48
45
  },
49
46
  "dependencies": {
50
- "hookified": "^1.15.0",
47
+ "hookified": "^2.1.0",
51
48
  "keyv": "^5.6.0",
52
- "@cacheable/utils": "^2.4.0"
49
+ "@cacheable/utils": "^2.4.1"
53
50
  },
54
51
  "files": [
55
52
  "dist",
@@ -57,7 +54,6 @@
57
54
  ],
58
55
  "scripts": {
59
56
  "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",
60
- "prepublish": "pnpm build",
61
57
  "lint": "biome check --write --error-on-warnings",
62
58
  "test": "pnpm lint && vitest run --coverage",
63
59
  "test:ci": "biome check --error-on-warnings && vitest run --coverage",