@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/README.md +109 -51
- package/dist/index.cjs +149 -68
- package/dist/index.d.cts +56 -32
- package/dist/index.d.ts +56 -32
- package/dist/index.js +149 -68
- package/package.json +5 -12
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
> Simple and Maintained fast Node.js caching
|
|
6
6
|
|
|
7
|
-
[](https://codecov.io/gh/jaredwray/cacheable)
|
|
7
|
+
[](https://codecov.io/gh/jaredwray/cacheable)
|
|
8
8
|
[](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml)
|
|
9
9
|
[](https://www.npmjs.com/package/@cacheable/node-cache)
|
|
10
10
|
[](https://www.npmjs.com/package/@cacheable/node-cache)
|
|
@@ -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'); //
|
|
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<
|
|
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 `
|
|
142
|
+
the `PartialNodeCacheItem` is defined as:
|
|
170
143
|
|
|
171
144
|
```javascript
|
|
172
|
-
export type
|
|
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'); //
|
|
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']); //
|
|
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']); //
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
260
|
+
cache.set('foo', 'bar');
|
|
288
261
|
cache.flushStats();
|
|
289
262
|
cache.getStats(); // {hits: 0, misses: 0, keys: 0, ksize: 0, vsize: 0}
|
|
290
|
-
|
|
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
|
|
357
|
-
* `mset(data: Array<
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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(
|
|
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
|
|
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
|
}
|
|
@@ -156,10 +132,10 @@ var NodeCacheStore = class extends import_hookified.Hookified {
|
|
|
156
132
|
const result = {};
|
|
157
133
|
for (const key of keys) {
|
|
158
134
|
const value = await this._keyv.get(key.toString());
|
|
159
|
-
if (value
|
|
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
|
|
175
|
-
|
|
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
|
|
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
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
}
|
|
@@ -285,29 +294,40 @@ var NodeCache = class extends import_hookified2.Hookified {
|
|
|
285
294
|
}
|
|
286
295
|
/**
|
|
287
296
|
* Sets a key value pair. It is possible to define a ttl (in seconds). Returns true on success.
|
|
297
|
+
*
|
|
298
|
+
* TTL behavior:
|
|
299
|
+
* - `ttl > 0`: cache expires after the given number of seconds
|
|
300
|
+
* - `ttl === 0`: cache indefinitely (overrides stdTTL)
|
|
301
|
+
* - `ttl < 0`: store the value but it expires immediately on next access (matches original node-cache behavior)
|
|
302
|
+
* - `ttl` omitted/undefined: use `stdTTL` from options (0 = unlimited if stdTTL is 0 or not set)
|
|
303
|
+
* - `ttl` as string: shorthand format like '1h', '30s', '5m', '2d'
|
|
304
|
+
*
|
|
288
305
|
* @param {string | number} key - it will convert the key to a string
|
|
289
306
|
* @param {T} value
|
|
290
|
-
* @param {number | string} [ttl] -
|
|
291
|
-
* @returns {boolean}
|
|
307
|
+
* @param {number | string} [ttl] - TTL in seconds. 0 = unlimited, negative = expires immediately, string = shorthand format
|
|
308
|
+
* @returns {boolean} true on success
|
|
309
|
+
* @throws {Error} If the `key` or `ttl` is of an invalid type.
|
|
292
310
|
*/
|
|
293
|
-
set(key, value, ttl
|
|
311
|
+
set(key, value, ttl) {
|
|
294
312
|
if (typeof key !== "string" && typeof key !== "number") {
|
|
295
313
|
throw this.createError("The key argument has to be of type `string` or `number`. Found: `__key`" /* EKEYTYPE */, key);
|
|
296
314
|
}
|
|
297
|
-
if (ttl && typeof ttl !== "number" && typeof ttl !== "string") {
|
|
315
|
+
if (ttl !== void 0 && typeof ttl !== "number" && typeof ttl !== "string") {
|
|
298
316
|
throw this.createError("The ttl argument has to be a number or a string for shorthand ttl." /* ETTLTYPE */, this.formatKey(key));
|
|
299
317
|
}
|
|
300
318
|
const keyValue = this.formatKey(key);
|
|
301
|
-
let ttlValue = 0;
|
|
302
|
-
if (this.options.stdTTL) {
|
|
303
|
-
ttlValue = this.getExpirationTimestamp(this.options.stdTTL);
|
|
304
|
-
}
|
|
305
|
-
if (ttl) {
|
|
306
|
-
ttlValue = this.getExpirationTimestamp(ttl);
|
|
307
|
-
}
|
|
308
319
|
let expirationTimestamp = 0;
|
|
309
|
-
if (
|
|
310
|
-
expirationTimestamp =
|
|
320
|
+
if (this.isNegativeTtl(ttl)) {
|
|
321
|
+
expirationTimestamp = Math.max(
|
|
322
|
+
1,
|
|
323
|
+
this.getExpirationTimestamp(
|
|
324
|
+
typeof ttl === "string" ? Number(ttl) : ttl
|
|
325
|
+
)
|
|
326
|
+
);
|
|
327
|
+
} else if (ttl !== void 0 && (typeof ttl === "string" || ttl > 0)) {
|
|
328
|
+
expirationTimestamp = this.resolveExpiration(ttl);
|
|
329
|
+
} else if (ttl === void 0 && this.options.stdTTL !== void 0 && this.options.stdTTL !== 0) {
|
|
330
|
+
expirationTimestamp = this.resolveExpiration(this.options.stdTTL);
|
|
311
331
|
}
|
|
312
332
|
if (this.options.maxKeys) {
|
|
313
333
|
const { maxKeys } = this.options;
|
|
@@ -320,7 +340,7 @@ var NodeCache = class extends import_hookified2.Hookified {
|
|
|
320
340
|
value,
|
|
321
341
|
ttl: expirationTimestamp
|
|
322
342
|
});
|
|
323
|
-
this.emit("set", keyValue, value,
|
|
343
|
+
this.emit("set", keyValue, value, expirationTimestamp);
|
|
324
344
|
this._stats.incrementKSize(keyValue);
|
|
325
345
|
this._stats.incrementVSize(value);
|
|
326
346
|
this._stats.setCount(this.store.size);
|
|
@@ -328,8 +348,16 @@ var NodeCache = class extends import_hookified2.Hookified {
|
|
|
328
348
|
}
|
|
329
349
|
/**
|
|
330
350
|
* Sets multiple key val pairs. It is possible to define a ttl (seconds). Returns true on success.
|
|
351
|
+
*
|
|
352
|
+
* Each item follows the same TTL behavior as `set()`:
|
|
353
|
+
* - Positive TTL: expires after the given seconds
|
|
354
|
+
* - `0`: cache indefinitely
|
|
355
|
+
* - Negative TTL: stored but expires immediately on next access
|
|
356
|
+
* - Omitted: uses `stdTTL` from options
|
|
357
|
+
*
|
|
331
358
|
* @param {PartialNodeCacheItem<T>[]} data an array of key value pairs with optional ttl
|
|
332
|
-
* @returns {boolean}
|
|
359
|
+
* @returns {boolean} true on success
|
|
360
|
+
* @throws {Error} If `data` is not an array, or if any item has an invalid key or ttl type.
|
|
333
361
|
*/
|
|
334
362
|
mset(data) {
|
|
335
363
|
if (!Array.isArray(data)) {
|
|
@@ -441,15 +469,41 @@ var NodeCache = class extends import_hookified2.Hookified {
|
|
|
441
469
|
/**
|
|
442
470
|
* Redefine the ttl of a key. Returns true if the key has been found and changed.
|
|
443
471
|
* Otherwise returns false. If the ttl-argument isn't passed the default-TTL will be used.
|
|
472
|
+
*
|
|
473
|
+
* TTL behavior:
|
|
474
|
+
* - `ttl > 0`: key expires after the given number of seconds
|
|
475
|
+
* - `ttl === 0`: key lives indefinitely (overrides stdTTL)
|
|
476
|
+
* - `ttl < 0`: key expires immediately on next access (matches original node-cache behavior)
|
|
477
|
+
* - `ttl` omitted/undefined: use `stdTTL` from options (0 = unlimited if stdTTL is 0 or not set)
|
|
478
|
+
* - `ttl` as string: shorthand format like '1h', '30s', '5m', '2d'
|
|
479
|
+
*
|
|
444
480
|
* @param {string | number} key if the key is a number it will convert it to a string
|
|
445
|
-
* @param {number | string} [ttl]
|
|
481
|
+
* @param {number | string} [ttl] TTL in seconds. 0 = unlimited, negative = expires immediately, string = shorthand format
|
|
446
482
|
* @returns {boolean} true if the key has been found and changed. Otherwise returns false.
|
|
483
|
+
* @throws {Error} If the `ttl` is of an invalid type (must be a number or string).
|
|
447
484
|
*/
|
|
448
485
|
ttl(key, ttl) {
|
|
486
|
+
if (ttl !== void 0 && typeof ttl !== "number" && typeof ttl !== "string") {
|
|
487
|
+
throw this.createError("The ttl argument has to be a number or a string for shorthand ttl." /* ETTLTYPE */, this.formatKey(key));
|
|
488
|
+
}
|
|
449
489
|
const result = this.store.get(this.formatKey(key));
|
|
450
490
|
if (result) {
|
|
451
|
-
|
|
452
|
-
|
|
491
|
+
if (this.isNegativeTtl(ttl)) {
|
|
492
|
+
result.ttl = Math.max(
|
|
493
|
+
1,
|
|
494
|
+
this.getExpirationTimestamp(
|
|
495
|
+
typeof ttl === "string" ? Number(ttl) : ttl
|
|
496
|
+
)
|
|
497
|
+
);
|
|
498
|
+
} else if (ttl !== void 0 && (typeof ttl === "string" || ttl > 0)) {
|
|
499
|
+
result.ttl = this.resolveExpiration(ttl);
|
|
500
|
+
} else if (ttl === 0) {
|
|
501
|
+
result.ttl = 0;
|
|
502
|
+
} else if (this.options.stdTTL !== void 0 && this.options.stdTTL !== 0) {
|
|
503
|
+
result.ttl = this.resolveExpiration(this.options.stdTTL);
|
|
504
|
+
} else {
|
|
505
|
+
result.ttl = 0;
|
|
506
|
+
}
|
|
453
507
|
this.store.set(this.formatKey(key), result);
|
|
454
508
|
return true;
|
|
455
509
|
}
|
|
@@ -573,6 +627,33 @@ var NodeCache = class extends import_hookified2.Hookified {
|
|
|
573
627
|
const expirationTimestamp = currentTimestamp + ttlInMilliseconds;
|
|
574
628
|
return expirationTimestamp;
|
|
575
629
|
}
|
|
630
|
+
/**
|
|
631
|
+
* Resolves a TTL value to an expiration timestamp, returning 0 (unlimited) if the
|
|
632
|
+
* resolved timestamp is not in the future (e.g. "0s" or a zero-duration string).
|
|
633
|
+
*/
|
|
634
|
+
resolveExpiration(ttl) {
|
|
635
|
+
const timestamp = this.getExpirationTimestamp(ttl);
|
|
636
|
+
if (timestamp <= Date.now()) {
|
|
637
|
+
return 0;
|
|
638
|
+
}
|
|
639
|
+
return timestamp;
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Checks whether a TTL value is negative. Handles both numbers and
|
|
643
|
+
* purely numeric strings (e.g. "-1").
|
|
644
|
+
*/
|
|
645
|
+
isNegativeTtl(ttl) {
|
|
646
|
+
if (typeof ttl === "number") {
|
|
647
|
+
return ttl < 0;
|
|
648
|
+
}
|
|
649
|
+
if (typeof ttl === "string") {
|
|
650
|
+
const num = Number(ttl);
|
|
651
|
+
if (!Number.isNaN(num) && num < 0) {
|
|
652
|
+
return true;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
576
657
|
checkData() {
|
|
577
658
|
for (const [key, value] of this.store.entries()) {
|
|
578
659
|
if (value.ttl > 0 && value.ttl < Date.now()) {
|