@cacheable/node-cache 2.0.1 → 3.0.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/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
  }
@@ -119,10 +95,10 @@ var NodeCacheStore = class extends Hookified {
119
95
  const result = {};
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
  }
@@ -248,29 +257,40 @@ var NodeCache = class extends Hookified2 {
248
257
  }
249
258
  /**
250
259
  * Sets a key value pair. It is possible to define a ttl (in seconds). Returns true on success.
260
+ *
261
+ * TTL behavior:
262
+ * - `ttl > 0`: cache expires after the given number of seconds
263
+ * - `ttl === 0`: cache indefinitely (overrides stdTTL)
264
+ * - `ttl < 0`: store the value but it expires immediately on next access (matches original node-cache behavior)
265
+ * - `ttl` omitted/undefined: use `stdTTL` from options (0 = unlimited if stdTTL is 0 or not set)
266
+ * - `ttl` as string: shorthand format like '1h', '30s', '5m', '2d'
267
+ *
251
268
  * @param {string | number} key - it will convert the key to a string
252
269
  * @param {T} value
253
- * @param {number | string} [ttl] - this is in seconds and undefined will use the default ttl
254
- * @returns {boolean}
270
+ * @param {number | string} [ttl] - TTL in seconds. 0 = unlimited, negative = expires immediately, string = shorthand format
271
+ * @returns {boolean} true on success
272
+ * @throws {Error} If the `key` or `ttl` is of an invalid type.
255
273
  */
256
- set(key, value, ttl = 0) {
274
+ set(key, value, ttl) {
257
275
  if (typeof key !== "string" && typeof key !== "number") {
258
276
  throw this.createError("The key argument has to be of type `string` or `number`. Found: `__key`" /* EKEYTYPE */, key);
259
277
  }
260
- if (ttl && typeof ttl !== "number" && typeof ttl !== "string") {
278
+ if (ttl !== void 0 && typeof ttl !== "number" && typeof ttl !== "string") {
261
279
  throw this.createError("The ttl argument has to be a number or a string for shorthand ttl." /* ETTLTYPE */, this.formatKey(key));
262
280
  }
263
281
  const keyValue = this.formatKey(key);
264
- let ttlValue = 0;
265
- if (this.options.stdTTL) {
266
- ttlValue = this.getExpirationTimestamp(this.options.stdTTL);
267
- }
268
- if (ttl) {
269
- ttlValue = this.getExpirationTimestamp(ttl);
270
- }
271
282
  let expirationTimestamp = 0;
272
- if (ttlValue && ttlValue > 0) {
273
- expirationTimestamp = ttlValue;
283
+ if (this.isNegativeTtl(ttl)) {
284
+ expirationTimestamp = Math.max(
285
+ 1,
286
+ this.getExpirationTimestamp(
287
+ typeof ttl === "string" ? Number(ttl) : ttl
288
+ )
289
+ );
290
+ } else if (ttl !== void 0 && (typeof ttl === "string" || ttl > 0)) {
291
+ expirationTimestamp = this.resolveExpiration(ttl);
292
+ } else if (ttl === void 0 && this.options.stdTTL !== void 0 && this.options.stdTTL !== 0) {
293
+ expirationTimestamp = this.resolveExpiration(this.options.stdTTL);
274
294
  }
275
295
  if (this.options.maxKeys) {
276
296
  const { maxKeys } = this.options;
@@ -283,7 +303,7 @@ var NodeCache = class extends Hookified2 {
283
303
  value,
284
304
  ttl: expirationTimestamp
285
305
  });
286
- this.emit("set", keyValue, value, ttlValue);
306
+ this.emit("set", keyValue, value, expirationTimestamp);
287
307
  this._stats.incrementKSize(keyValue);
288
308
  this._stats.incrementVSize(value);
289
309
  this._stats.setCount(this.store.size);
@@ -291,8 +311,16 @@ var NodeCache = class extends Hookified2 {
291
311
  }
292
312
  /**
293
313
  * Sets multiple key val pairs. It is possible to define a ttl (seconds). Returns true on success.
314
+ *
315
+ * Each item follows the same TTL behavior as `set()`:
316
+ * - Positive TTL: expires after the given seconds
317
+ * - `0`: cache indefinitely
318
+ * - Negative TTL: stored but expires immediately on next access
319
+ * - Omitted: uses `stdTTL` from options
320
+ *
294
321
  * @param {PartialNodeCacheItem<T>[]} data an array of key value pairs with optional ttl
295
- * @returns {boolean}
322
+ * @returns {boolean} true on success
323
+ * @throws {Error} If `data` is not an array, or if any item has an invalid key or ttl type.
296
324
  */
297
325
  mset(data) {
298
326
  if (!Array.isArray(data)) {
@@ -404,15 +432,41 @@ var NodeCache = class extends Hookified2 {
404
432
  /**
405
433
  * Redefine the ttl of a key. Returns true if the key has been found and changed.
406
434
  * Otherwise returns false. If the ttl-argument isn't passed the default-TTL will be used.
435
+ *
436
+ * TTL behavior:
437
+ * - `ttl > 0`: key expires after the given number of seconds
438
+ * - `ttl === 0`: key lives indefinitely (overrides stdTTL)
439
+ * - `ttl < 0`: key expires immediately on next access (matches original node-cache behavior)
440
+ * - `ttl` omitted/undefined: use `stdTTL` from options (0 = unlimited if stdTTL is 0 or not set)
441
+ * - `ttl` as string: shorthand format like '1h', '30s', '5m', '2d'
442
+ *
407
443
  * @param {string | number} key if the key is a number it will convert it to a string
408
- * @param {number | string} [ttl] the ttl in seconds if number, or a shorthand string like '1h' for 1 hour
444
+ * @param {number | string} [ttl] TTL in seconds. 0 = unlimited, negative = expires immediately, string = shorthand format
409
445
  * @returns {boolean} true if the key has been found and changed. Otherwise returns false.
446
+ * @throws {Error} If the `ttl` is of an invalid type (must be a number or string).
410
447
  */
411
448
  ttl(key, ttl) {
449
+ if (ttl !== void 0 && typeof ttl !== "number" && typeof ttl !== "string") {
450
+ throw this.createError("The ttl argument has to be a number or a string for shorthand ttl." /* ETTLTYPE */, this.formatKey(key));
451
+ }
412
452
  const result = this.store.get(this.formatKey(key));
413
453
  if (result) {
414
- const ttlValue = ttl ?? this.options.stdTTL;
415
- result.ttl = this.getExpirationTimestamp(ttlValue);
454
+ if (this.isNegativeTtl(ttl)) {
455
+ result.ttl = Math.max(
456
+ 1,
457
+ this.getExpirationTimestamp(
458
+ typeof ttl === "string" ? Number(ttl) : ttl
459
+ )
460
+ );
461
+ } else if (ttl !== void 0 && (typeof ttl === "string" || ttl > 0)) {
462
+ result.ttl = this.resolveExpiration(ttl);
463
+ } else if (ttl === 0) {
464
+ result.ttl = 0;
465
+ } else if (this.options.stdTTL !== void 0 && this.options.stdTTL !== 0) {
466
+ result.ttl = this.resolveExpiration(this.options.stdTTL);
467
+ } else {
468
+ result.ttl = 0;
469
+ }
416
470
  this.store.set(this.formatKey(key), result);
417
471
  return true;
418
472
  }
@@ -536,6 +590,33 @@ var NodeCache = class extends Hookified2 {
536
590
  const expirationTimestamp = currentTimestamp + ttlInMilliseconds;
537
591
  return expirationTimestamp;
538
592
  }
593
+ /**
594
+ * Resolves a TTL value to an expiration timestamp, returning 0 (unlimited) if the
595
+ * resolved timestamp is not in the future (e.g. "0s" or a zero-duration string).
596
+ */
597
+ resolveExpiration(ttl) {
598
+ const timestamp = this.getExpirationTimestamp(ttl);
599
+ if (timestamp <= Date.now()) {
600
+ return 0;
601
+ }
602
+ return timestamp;
603
+ }
604
+ /**
605
+ * Checks whether a TTL value is negative. Handles both numbers and
606
+ * purely numeric strings (e.g. "-1").
607
+ */
608
+ isNegativeTtl(ttl) {
609
+ if (typeof ttl === "number") {
610
+ return ttl < 0;
611
+ }
612
+ if (typeof ttl === "string") {
613
+ const num = Number(ttl);
614
+ if (!Number.isNaN(num) && num < 0) {
615
+ return true;
616
+ }
617
+ }
618
+ return false;
619
+ }
539
620
  checkData() {
540
621
  for (const [key, value] of this.store.entries()) {
541
622
  if (value.ttl > 0 && value.ttl < Date.now()) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cacheable/node-cache",
3
- "version": "2.0.1",
3
+ "version": "3.0.0",
4
4
  "description": "Simple and Maintained fast NodeJS internal caching",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -40,19 +40,13 @@
40
40
  "cacheable-node"
41
41
  ],
42
42
  "devDependencies": {
43
- "@biomejs/biome": "^2.3.11",
44
- "@faker-js/faker": "^10.2.0",
45
- "@types/node": "^25.0.8",
46
- "@vitest/coverage-v8": "^4.0.17",
47
- "rimraf": "^6.1.2",
48
43
  "tsup": "^8.5.1",
49
- "typescript": "^5.9.3",
50
- "vitest": "^4.0.17"
44
+ "typescript": "^5.9.3"
51
45
  },
52
46
  "dependencies": {
53
- "hookified": "^1.15.0",
54
- "keyv": "^5.5.5",
55
- "@cacheable/utils": "^2.3.3"
47
+ "hookified": "^2.1.0",
48
+ "keyv": "^5.6.0",
49
+ "@cacheable/utils": "^2.4.1"
56
50
  },
57
51
  "files": [
58
52
  "dist",
@@ -60,7 +54,6 @@
60
54
  ],
61
55
  "scripts": {
62
56
  "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",
63
- "prepublish": "pnpm build",
64
57
  "lint": "biome check --write --error-on-warnings",
65
58
  "test": "pnpm lint && vitest run --coverage",
66
59
  "test:ci": "biome check --error-on-warnings && vitest run --coverage",