keyv 6.0.0-beta.3 → 6.0.0-rc.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/LICENSE +0 -10
- package/README.md +262 -135
- package/dist/index.cjs +169 -86
- package/dist/index.d.cts +279 -110
- package/dist/index.d.mts +279 -110
- package/dist/index.mjs +169 -87
- package/package.json +9 -9
package/README.md
CHANGED
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
[](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml)
|
|
6
6
|
[](https://github.com/jaredwray/keyv/actions/workflows/bun-test.yaml)
|
|
7
7
|
[](https://github.com/jaredwray/keyv/actions/workflows/browser-compat.yaml)
|
|
8
|
-
[](https://www.jsdelivr.com/package/npm/keyv)
|
|
9
|
+
[](https://codecov.io/gh/jaredwray/keyv)
|
|
9
10
|
[](https://www.npmjs.com/package/keyv)
|
|
10
11
|
[](https://www.npmjs.com/package/keyv)
|
|
11
|
-
|
|
12
|
+
|
|
12
13
|
Keyv provides a consistent interface for key-value storage across multiple backends via storage adapters. It supports TTL based expiry, making it suitable as a cache or a persistent key-value store.
|
|
13
14
|
|
|
14
15
|
# Features
|
|
@@ -36,6 +37,7 @@ There are a few existing modules similar to Keyv, however Keyv is different beca
|
|
|
36
37
|
- [Serialization](#serialization)
|
|
37
38
|
- [Official Storage Adapters](#official-storage-adapters)
|
|
38
39
|
- [Third-party Storage Adapters](#third-party-storage-adapters)
|
|
40
|
+
- [Built-in Adapters: Memory and Bridge](#built-in-adapters-memory-and-bridge)
|
|
39
41
|
- [Using BigMap to Scale](#using-bigmap-to-scale)
|
|
40
42
|
- [Compression](#compression)
|
|
41
43
|
- [Capability Detection](#capability-detection)
|
|
@@ -45,17 +47,17 @@ There are a few existing modules similar to Keyv, however Keyv is different beca
|
|
|
45
47
|
- [.ttl](#ttl)
|
|
46
48
|
- [.store](#store)
|
|
47
49
|
- [.serialization](#serialization-1)
|
|
48
|
-
- [.compression](#compression)
|
|
49
|
-
- [.
|
|
50
|
-
- [.emitErrors](#emiterrors)
|
|
50
|
+
- [.compression](#compression-1)
|
|
51
|
+
- [.encryption](#encryption-1)
|
|
51
52
|
- [.throwOnErrors](#throwonerrors)
|
|
53
|
+
- [.checkExpired](#checkexpired)
|
|
52
54
|
- [.stats](#stats)
|
|
53
55
|
- [.sanitize](#sanitize)
|
|
54
56
|
- [Keyv Instance](#keyv-instance)
|
|
55
57
|
- [.set(key, value, [ttl])](#setkey-value-ttl)
|
|
56
58
|
- [.setMany(entries)](#setmanyentries)
|
|
57
|
-
- [.get(key
|
|
58
|
-
- [.getMany(keys
|
|
59
|
+
- [.get(key)](#getkey)
|
|
60
|
+
- [.getMany(keys)](#getmanykeys)
|
|
59
61
|
- [.getRaw(key)](#getrawkey)
|
|
60
62
|
- [.getManyRaw(keys)](#getmanyrawkeys)
|
|
61
63
|
- [.setRaw(key, value)](#setrawkey-value)
|
|
@@ -192,12 +194,11 @@ await cache.get('foo'); // 'cache'
|
|
|
192
194
|
|
|
193
195
|
# Events
|
|
194
196
|
|
|
195
|
-
Keyv is
|
|
196
|
-
If there is no listener for the `'error'` event, an uncaught exception will be thrown.
|
|
197
|
-
To disable the `'error'` event, pass `emitErrors: false` in the constructor options.
|
|
197
|
+
Keyv is an `EventEmitter` (built on [hookified](https://github.com/jaredwray/hookified)) and will emit an `'error'` event if there is an error. By default an error is only thrown if there are no listeners attached to the `'error'` event. To always throw on errors regardless of listeners, enable the [`throwOnErrors`](#throwonerrors) option.
|
|
198
198
|
|
|
199
199
|
```js
|
|
200
|
-
const keyv = new Keyv(
|
|
200
|
+
const keyv = new Keyv();
|
|
201
|
+
keyv.on('error', err => console.log('Connection Error', err));
|
|
201
202
|
```
|
|
202
203
|
|
|
203
204
|
In addition it will emit `clear` and `disconnect` events when the corresponding methods are called.
|
|
@@ -215,41 +216,46 @@ keyv.on('disconnect', handleDisconnect);
|
|
|
215
216
|
|
|
216
217
|
# Hooks
|
|
217
218
|
|
|
218
|
-
Keyv supports hooks for
|
|
219
|
+
Keyv supports hooks for all of its operations. Hooks are useful for logging, debugging, and other custom functionality. Each operation fires a `BEFORE_*` hook before it runs and an `AFTER_*` hook after it completes. Here is the list of all the hooks:
|
|
219
220
|
|
|
220
221
|
```
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
PRE_DELETE
|
|
236
|
-
POST_DELETE
|
|
222
|
+
BEFORE_GET / AFTER_GET
|
|
223
|
+
BEFORE_GET_MANY / AFTER_GET_MANY
|
|
224
|
+
BEFORE_GET_RAW / AFTER_GET_RAW
|
|
225
|
+
BEFORE_GET_MANY_RAW / AFTER_GET_MANY_RAW
|
|
226
|
+
BEFORE_SET / AFTER_SET
|
|
227
|
+
BEFORE_SET_RAW / AFTER_SET_RAW
|
|
228
|
+
BEFORE_SET_MANY / AFTER_SET_MANY
|
|
229
|
+
BEFORE_SET_MANY_RAW / AFTER_SET_MANY_RAW
|
|
230
|
+
BEFORE_DELETE / AFTER_DELETE
|
|
231
|
+
BEFORE_DELETE_MANY / AFTER_DELETE_MANY
|
|
232
|
+
BEFORE_HAS / AFTER_HAS
|
|
233
|
+
BEFORE_HAS_MANY / AFTER_HAS_MANY
|
|
234
|
+
BEFORE_CLEAR / AFTER_CLEAR
|
|
235
|
+
BEFORE_DISCONNECT / AFTER_DISCONNECT
|
|
237
236
|
```
|
|
238
237
|
|
|
239
|
-
|
|
238
|
+
> The older `PRE_*` / `POST_*` hook names (e.g. `PRE_GET`, `POST_SET`) are deprecated aliases that still fire for backward compatibility. Prefer the `BEFORE_*` / `AFTER_*` names going forward.
|
|
239
|
+
|
|
240
|
+
You can access these by importing `KeyvHooks` from the main Keyv package and registering a handler with `onHook()`:
|
|
240
241
|
|
|
241
242
|
```js
|
|
242
243
|
import Keyv, { KeyvHooks } from 'keyv';
|
|
244
|
+
|
|
245
|
+
const keyv = new Keyv();
|
|
246
|
+
keyv.onHook(KeyvHooks.BEFORE_SET, (data) => {
|
|
247
|
+
console.log(`Setting key ${data.key} to ${data.value}`);
|
|
248
|
+
});
|
|
243
249
|
```
|
|
244
250
|
|
|
245
251
|
## Get Hooks
|
|
246
252
|
|
|
247
|
-
The `
|
|
253
|
+
The `AFTER_GET` and `AFTER_GET_RAW` hooks fire on both cache hits and misses. When a cache miss occurs (key doesn't exist or is expired), the hook receives `undefined` as the value.
|
|
248
254
|
|
|
249
255
|
```js
|
|
250
|
-
//
|
|
256
|
+
// AFTER_GET hook - fires on both hits and misses
|
|
251
257
|
const keyv = new Keyv();
|
|
252
|
-
keyv.
|
|
258
|
+
keyv.onHook(KeyvHooks.AFTER_GET, (data) => {
|
|
253
259
|
if (data.value === undefined) {
|
|
254
260
|
console.log(`Cache miss for key: ${data.key}`);
|
|
255
261
|
} else {
|
|
@@ -262,9 +268,9 @@ await keyv.get('missing-key'); // Logs cache miss with undefined
|
|
|
262
268
|
```
|
|
263
269
|
|
|
264
270
|
```js
|
|
265
|
-
//
|
|
271
|
+
// AFTER_GET_RAW hook - same behavior as AFTER_GET
|
|
266
272
|
const keyv = new Keyv();
|
|
267
|
-
keyv.
|
|
273
|
+
keyv.onHook(KeyvHooks.AFTER_GET_RAW, (data) => {
|
|
268
274
|
console.log(`Key: ${data.key}, Value:`, data.value);
|
|
269
275
|
});
|
|
270
276
|
|
|
@@ -274,31 +280,31 @@ await keyv.getRaw('foo'); // Logs with value or undefined
|
|
|
274
280
|
## Set Hooks
|
|
275
281
|
|
|
276
282
|
```js
|
|
277
|
-
//
|
|
283
|
+
// BEFORE_SET hook
|
|
278
284
|
const keyv = new Keyv();
|
|
279
|
-
keyv.
|
|
285
|
+
keyv.onHook(KeyvHooks.BEFORE_SET, (data) => console.log(`Setting key ${data.key} to ${data.value}`));
|
|
280
286
|
|
|
281
|
-
//
|
|
287
|
+
// AFTER_SET hook
|
|
282
288
|
const keyv = new Keyv();
|
|
283
|
-
keyv.
|
|
289
|
+
keyv.onHook(KeyvHooks.AFTER_SET, ({ key, value }) => console.log(`Set key ${key} to ${value}`));
|
|
284
290
|
```
|
|
285
291
|
|
|
286
|
-
In
|
|
292
|
+
In the `BEFORE_SET` hook you can also manipulate the value before it is set. For example, you could add a prefix to all keys.
|
|
287
293
|
|
|
288
294
|
```js
|
|
289
295
|
const keyv = new Keyv();
|
|
290
|
-
keyv.
|
|
296
|
+
keyv.onHook(KeyvHooks.BEFORE_SET, (data) => {
|
|
291
297
|
console.log(`Manipulating key ${data.key} and ${data.value}`);
|
|
292
298
|
data.key = `prefix-${data.key}`;
|
|
293
299
|
data.value = `prefix-${data.value}`;
|
|
294
300
|
});
|
|
295
301
|
```
|
|
296
302
|
|
|
297
|
-
Now this key will have prefix
|
|
303
|
+
Now this key will have `prefix-` added to it before it is set.
|
|
298
304
|
|
|
299
305
|
## Delete Hooks
|
|
300
306
|
|
|
301
|
-
In `
|
|
307
|
+
In the `BEFORE_DELETE` and `AFTER_DELETE` hooks, the value could be a single item or an `Array`. This is based on the fact that `delete` can accept a single key or an `Array` of keys.
|
|
302
308
|
|
|
303
309
|
|
|
304
310
|
# Serialization
|
|
@@ -352,13 +358,13 @@ const keyv = new Keyv({ serialization: false });
|
|
|
352
358
|
|
|
353
359
|
## Pipeline
|
|
354
360
|
|
|
355
|
-
When serialization and/or
|
|
361
|
+
When serialization, compression, and/or encryption are configured, Keyv applies them in this order:
|
|
356
362
|
|
|
357
|
-
**On set:** serialize (optional) →
|
|
363
|
+
**On set:** serialize → compress (optional) → encrypt (optional) → store
|
|
358
364
|
|
|
359
|
-
**On get:** store →
|
|
365
|
+
**On get:** store → decrypt (optional) → decompress (optional) → parse → value
|
|
360
366
|
|
|
361
|
-
|
|
367
|
+
Compression and encryption operate on the serialized string, so they only run when a serializer is configured. The built-in `KeyvJsonSerializer` is enabled by default, so this works out of the box. If you disable serialization with `serialization: false`, values are passed through to the store as-is and compression/encryption are skipped.
|
|
362
368
|
|
|
363
369
|
# Official Storage Adapters
|
|
364
370
|
|
|
@@ -407,6 +413,86 @@ const keyv = new Keyv({ store: lru });
|
|
|
407
413
|
|
|
408
414
|
View the complete list of third-party storage adapters and learn how to build your own at https://keyv.org/docs/third-party-storage-adapters/
|
|
409
415
|
|
|
416
|
+
## Storage Adapter Contract (v6)
|
|
417
|
+
|
|
418
|
+
> The public API above is unchanged — `keyv.set(key, value, ttl)` still takes a relative TTL in milliseconds. The change below only affects authors of custom **storage adapters**.
|
|
419
|
+
|
|
420
|
+
As of v6, Keyv passes an **absolute `expires`** timestamp (Unix ms since epoch) to a storage adapter's write methods instead of a relative TTL. Keyv computes `expires` once, so adapters never need to derive or parse it:
|
|
421
|
+
|
|
422
|
+
```ts
|
|
423
|
+
import { keyvStorageCapability } from 'keyv';
|
|
424
|
+
|
|
425
|
+
type KeyvStorageEntry<Value> = { key: string; value: Value; expires?: number };
|
|
426
|
+
|
|
427
|
+
class MyAdapter {
|
|
428
|
+
// Declare support for the absolute-`expires` contract:
|
|
429
|
+
get capabilities() {
|
|
430
|
+
return keyvStorageCapability(this); // -> { ...detected, expires: true }
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// `expires` is absolute Unix ms; `undefined` means no expiry; `<= Date.now()` means already expired.
|
|
434
|
+
async set(key: string, value: unknown, expires?: number): Promise<boolean> { /* ... */ }
|
|
435
|
+
async setMany<Value>(entries: KeyvStorageEntry<Value>[]): Promise<boolean[] | undefined> { /* ... */ }
|
|
436
|
+
// ...get, delete, clear, has, getMany, deleteMany, hasMany, etc.
|
|
437
|
+
}
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
A v6 adapter declares `capabilities.expires === true` (the `keyvStorageCapability(this)` helper sets it for you). Keyv then passes the absolute `expires` to it directly — this takes precedence over structural detection, so an adapter whose methods aren't written with `async` is still used directly rather than bridged. Any **legacy** storage adapter that does *not* declare `capabilities.expires` is treated as a relative-TTL adapter and transparently wrapped by [`KeyvBridgeAdapter`](#built-in-adapters-memory-and-bridge), which converts the absolute `expires` back to a relative TTL before delegating (and deletes outright when the deadline has already elapsed) — so existing third-party adapters keep working unchanged. Stores that expose absolute-expiry primitives (e.g. Redis `PXAT`) use `expires` directly. Map-like stores wrapped via `new Keyv({ store: new Map() })` are unaffected.
|
|
441
|
+
|
|
442
|
+
> **Adapters should enforce expiry — and Keyv double-checks by default.** Declaring `capabilities.expires === true` means a v6 adapter should enforce expiry itself — ideally via a native mechanism (key expiry, TTL index, lease) so the backend reclaims space, and/or a client-side check on read. On top of that, Keyv core filters expired reads at its own layer by default ([`checkExpired`](#checkexpired) is `true`), using the absolute `expires` in the serialized envelope, so `get`/`getMany`/`has` never surface a key past its deadline even on backends whose native expiry is coarse or lazily swept (e.g. Memcached, DynamoDB). Run `@keyv/test-suite`'s `storageTtlTests` against your adapter to verify its own expiry behaviour.
|
|
443
|
+
|
|
444
|
+
# Built-in Adapters: Memory and Bridge
|
|
445
|
+
|
|
446
|
+
Keyv ships with two storage adapters built directly into the core package. You rarely instantiate them yourself — Keyv selects and wires up the right one automatically when you create an instance — but knowing how they work explains how the default in-memory store behaves and how legacy or async stores are adapted to the v6 contract. Both are exported from `keyv`:
|
|
447
|
+
|
|
448
|
+
## KeyvMemoryAdapter
|
|
449
|
+
|
|
450
|
+
`KeyvMemoryAdapter` is the **default store**. When you create a Keyv instance without a store (`new Keyv()`), it uses `new KeyvMemoryAdapter(new Map())` under the hood. It wraps any synchronous, `Map`-like object — the built-in `Map`, [`quick-lru`](https://github.com/sindresorhus/quick-lru), [`lru.min`](https://github.com/wellwelwel/lru.min), or anything exposing `get`, `set`, `delete`, `clear`, and `has`.
|
|
451
|
+
|
|
452
|
+
It adds the pieces a raw `Map` does not have:
|
|
453
|
+
|
|
454
|
+
- **Namespace prefixing** — keys are prefixed with the `namespace` and `keySeparator` (default `:`), so one underlying store can host multiple namespaces. A namespaced `clear()` removes only the current namespace's keys **when the underlying store exposes a `keys()` method** (a standard `Map` does); a minimal store without `keys()` falls back to wiping the **entire** store, so take care sharing one such store across namespaces.
|
|
455
|
+
- **TTL expiry** — the adapter keeps a copy of each entry's expiry in its own `{ value, expires }` wrapper *alongside* the stored value, so it can evict expired entries lazily on `get`, `getMany`, `has`, and `iterator()` without decoding the value. This wrapper is **separate from** the `{ value, expires }` envelope Keyv core builds and runs through serialization/compression/encryption — with the default serializer that encoded payload still contains `expires`, so custom serializer/encryption adapters must still handle the `expires` field; only the adapter's outer copy lives outside the payload. When the underlying store accepts a TTL argument (e.g. QuickLRU), the adapter also passes a derived relative duration so the store can evict on its own.
|
|
456
|
+
- **Batch and iteration** — `getMany`, `setMany`, `hasMany`, `deleteMany`, and an async `iterator()` (when the store supports `entries()`).
|
|
457
|
+
- **v6 contract** — declares `capabilities.expires === true`, so Keyv hands it the absolute `expires` timestamp directly and trusts it to enforce expiry.
|
|
458
|
+
|
|
459
|
+
```js
|
|
460
|
+
import Keyv, { KeyvMemoryAdapter } from 'keyv';
|
|
461
|
+
|
|
462
|
+
// Wrap any Map-like store. Put the namespace on the Keyv options, not the adapter: Keyv
|
|
463
|
+
// propagates its own namespace to the store, overwriting any namespace set on the adapter.
|
|
464
|
+
const keyv = new Keyv({ store: new KeyvMemoryAdapter(new Map()), namespace: 'cache' });
|
|
465
|
+
|
|
466
|
+
// Or wrap an LRU to bound memory usage
|
|
467
|
+
import QuickLRU from 'quick-lru';
|
|
468
|
+
const cache = new Keyv({ store: new KeyvMemoryAdapter(new QuickLRU({ maxSize: 1000 })) });
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
## KeyvBridgeAdapter
|
|
472
|
+
|
|
473
|
+
`KeyvBridgeAdapter` wraps any **promise-based / async store** and adapts it to the v6 storage contract. Keyv applies it automatically when you pass:
|
|
474
|
+
|
|
475
|
+
- a **legacy storage adapter** — a full async adapter that does *not* declare `capabilities.expires` (i.e. pre-v6 third-party adapters), or
|
|
476
|
+
- an **async `Map`-like store** with async `get`, `set`, `delete`, and `clear`. For such a store to actually expire data, its `set(key, value, ttl)` must honor the relative millisecond `ttl` the bridge passes as the third argument — a plain Promise-wrapped `Map` that ignores it won't evict on its own. Keyv's `checkExpired` (on by default) still filters expired entries on read, but they linger in the store until read; for native eviction, prefer a full v6 adapter or a store that honors the `ttl`.
|
|
477
|
+
|
|
478
|
+
This is why existing third-party adapters keep working unchanged on v6. The bridge:
|
|
479
|
+
|
|
480
|
+
- **Converts expiry** — Keyv passes an absolute `expires` timestamp; the bridge converts it back to the relative TTL the wrapped store expects. A write whose deadline has already elapsed is deleted instead of stored, so a past `expires` becomes an absent key — matching how the native adapters treat an already-expired write.
|
|
481
|
+
- **Delegates when it can** — if the wrapped store implements `getMany`, `setMany`, `has`, `hasMany`, `deleteMany`, `iterator`, or `disconnect`, the bridge calls them directly; otherwise it falls back to looping over the single-key primitives.
|
|
482
|
+
- **Handles namespacing both ways** — if the wrapped store manages its own namespace (a full adapter exposing a `namespace` property), the bridge propagates its namespace to the store and does *not* prefix keys, avoiding double-namespacing, so the store's native scoped `clear()` and `iterator()` are used. Otherwise the bridge prefixes keys itself, letting one shared store host multiple namespaces.
|
|
483
|
+
- **Forwards errors** — re-emits `error` events from the wrapped store so connection failures surface on the Keyv instance.
|
|
484
|
+
|
|
485
|
+
```js
|
|
486
|
+
import Keyv, { KeyvBridgeAdapter } from 'keyv';
|
|
487
|
+
|
|
488
|
+
// Usually automatic — just pass the store:
|
|
489
|
+
const keyv = new Keyv({ store: myAsyncStore });
|
|
490
|
+
|
|
491
|
+
// ...which is equivalent to wrapping it explicitly. Put the namespace on the Keyv options —
|
|
492
|
+
// Keyv overwrites any namespace set on the adapter directly:
|
|
493
|
+
const explicit = new Keyv({ store: new KeyvBridgeAdapter(myAsyncStore), namespace: 'cache' });
|
|
494
|
+
```
|
|
495
|
+
|
|
410
496
|
# Using BigMap to Scale
|
|
411
497
|
|
|
412
498
|
## Understanding JavaScript Map Limitations
|
|
@@ -517,7 +603,7 @@ keyvCompressionTests(test, new KeyvGzip());
|
|
|
517
603
|
|
|
518
604
|
# Encryption
|
|
519
605
|
|
|
520
|
-
Keyv
|
|
606
|
+
Keyv supports pluggable encryption of stored values via the `KeyvEncryptionAdapter` interface. Pass an adapter with `encrypt` and `decrypt` methods using the `encryption` option (or set the [`.encryption`](#encryption-1) property). Encryption runs on the serialized (and optionally compressed) value, so it requires a serializer — the built-in `KeyvJsonSerializer` is enabled by default.
|
|
521
607
|
|
|
522
608
|
```typescript
|
|
523
609
|
interface KeyvEncryptionAdapter {
|
|
@@ -526,9 +612,22 @@ interface KeyvEncryptionAdapter {
|
|
|
526
612
|
}
|
|
527
613
|
```
|
|
528
614
|
|
|
615
|
+
```js
|
|
616
|
+
import Keyv from 'keyv';
|
|
617
|
+
|
|
618
|
+
const encryption = {
|
|
619
|
+
encrypt: async (data) => Buffer.from(data).toString('base64'),
|
|
620
|
+
decrypt: async (data) => Buffer.from(data, 'base64').toString('utf8'),
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
const keyv = new Keyv({ encryption });
|
|
624
|
+
await keyv.set('foo', 'bar'); // value is encrypted at rest
|
|
625
|
+
await keyv.get('foo'); // 'bar'
|
|
626
|
+
```
|
|
627
|
+
|
|
529
628
|
# Capability Detection
|
|
530
629
|
|
|
531
|
-
Keyv exports helper functions to check whether an object implements the expected interface for a Keyv instance, storage adapter, compression adapter, serialization adapter, or encryption adapter. Each function returns an object with
|
|
630
|
+
Keyv exports helper functions to check whether an object implements the expected interface for a Keyv instance, storage adapter, compression adapter, serialization adapter, or encryption adapter. Each function returns an object with a top-level `compatible` boolean (whether the object fully satisfies the interface) plus a `methods` record describing every method it looked for.
|
|
532
631
|
|
|
533
632
|
```ts
|
|
534
633
|
import {
|
|
@@ -537,43 +636,47 @@ import {
|
|
|
537
636
|
detectKeyvCompression,
|
|
538
637
|
detectKeyvSerialization,
|
|
539
638
|
detectKeyvEncryption,
|
|
540
|
-
detectCapabilities,
|
|
541
639
|
} from 'keyv';
|
|
542
640
|
```
|
|
543
641
|
|
|
642
|
+
Every entry in the `methods` record has the shape `{ exists: boolean, methodType: "sync" | "async" | "none" }`.
|
|
643
|
+
|
|
544
644
|
## detectKeyv(obj)
|
|
545
645
|
|
|
546
|
-
Returns a `KeyvCapability`
|
|
646
|
+
Returns a `KeyvCapability`: `{ compatible, methods, properties }`. `compatible` is `true` only when **all** Keyv methods and properties are present.
|
|
547
647
|
|
|
548
648
|
```ts
|
|
549
649
|
import Keyv, { detectKeyv } from 'keyv';
|
|
550
650
|
|
|
551
|
-
detectKeyv(new Keyv());
|
|
552
|
-
//
|
|
553
|
-
//
|
|
554
|
-
//
|
|
555
|
-
//
|
|
651
|
+
const result = detectKeyv(new Keyv());
|
|
652
|
+
result.compatible; // true — all capabilities present
|
|
653
|
+
result.methods.get.exists; // true
|
|
654
|
+
result.methods.get.methodType; // "async"
|
|
655
|
+
result.properties.hooks; // true
|
|
656
|
+
result.properties.stats; // true
|
|
556
657
|
|
|
557
|
-
detectKeyv(new Map());
|
|
558
|
-
//
|
|
658
|
+
const partial = detectKeyv(new Map());
|
|
659
|
+
partial.compatible; // false — missing getMany, setMany, hooks, stats, etc.
|
|
660
|
+
partial.methods.get.exists; // true
|
|
559
661
|
```
|
|
560
662
|
|
|
561
663
|
## detectKeyvStorage(obj)
|
|
562
664
|
|
|
563
|
-
Returns a `KeyvStorageCapability`.
|
|
665
|
+
Returns a `KeyvStorageCapability`: `{ compatible, store, methods }`. `compatible` is `true` when the object is a usable storage adapter, and `store` reports the detected kind:
|
|
564
666
|
|
|
565
|
-
|
|
566
|
-
- **`mapLike`** —
|
|
567
|
-
- **`
|
|
667
|
+
- **`"keyvStorage"`** — implements the full async storage adapter interface (`get`, `set`, `delete`, `clear`, `has`, `setMany`, `deleteMany`, `hasMany`, all async)
|
|
668
|
+
- **`"mapLike"`** — has synchronous `get`, `set`, `delete`, and `has` (i.e. it behaves like a `Map`)
|
|
669
|
+
- **`"asyncMap"`** — has at least async `get`, `set`, `delete`, and `clear`
|
|
670
|
+
- **`"none"`** — not a usable store
|
|
568
671
|
|
|
569
672
|
```ts
|
|
570
673
|
import { detectKeyvStorage } from 'keyv';
|
|
571
674
|
|
|
572
675
|
// Map-like object
|
|
573
|
-
const
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
676
|
+
const map = detectKeyvStorage(new Map());
|
|
677
|
+
map.compatible; // true
|
|
678
|
+
map.store; // "mapLike"
|
|
679
|
+
map.methods.get.methodType; // "sync"
|
|
577
680
|
|
|
578
681
|
// Async storage adapter
|
|
579
682
|
const adapter = {
|
|
@@ -582,58 +685,48 @@ const adapter = {
|
|
|
582
685
|
deleteMany: async () => {}, hasMany: async () => {},
|
|
583
686
|
};
|
|
584
687
|
const adapterResult = detectKeyvStorage(adapter);
|
|
585
|
-
adapterResult.
|
|
586
|
-
adapterResult.
|
|
587
|
-
adapterResult.
|
|
688
|
+
adapterResult.compatible; // true
|
|
689
|
+
adapterResult.store; // "keyvStorage"
|
|
690
|
+
adapterResult.methods.get.methodType; // "async"
|
|
588
691
|
```
|
|
589
692
|
|
|
590
693
|
## detectKeyvCompression(obj)
|
|
591
694
|
|
|
592
|
-
Returns a `KeyvCompressionCapability`.
|
|
695
|
+
Returns a `KeyvCompressionCapability`: `{ compatible, methods }`. `compatible` is `true` when both `compress` and `decompress` methods are present.
|
|
593
696
|
|
|
594
697
|
```ts
|
|
595
698
|
import { detectKeyvCompression } from 'keyv';
|
|
596
699
|
|
|
597
|
-
detectKeyvCompression({ compress: (d) => d, decompress: (d) => d });
|
|
598
|
-
//
|
|
700
|
+
const result = detectKeyvCompression({ compress: (d) => d, decompress: (d) => d });
|
|
701
|
+
result.compatible; // true
|
|
702
|
+
result.methods.compress.exists; // true
|
|
703
|
+
result.methods.decompress.exists; // true
|
|
599
704
|
```
|
|
600
705
|
|
|
601
706
|
## detectKeyvSerialization(obj)
|
|
602
707
|
|
|
603
|
-
Returns a `KeyvSerializationCapability`.
|
|
708
|
+
Returns a `KeyvSerializationCapability`: `{ compatible, methods }`. `compatible` is `true` when both `stringify` and `parse` methods are present.
|
|
604
709
|
|
|
605
710
|
```ts
|
|
606
711
|
import { detectKeyvSerialization } from 'keyv';
|
|
607
712
|
|
|
608
|
-
detectKeyvSerialization(JSON);
|
|
609
|
-
//
|
|
713
|
+
const result = detectKeyvSerialization(JSON);
|
|
714
|
+
result.compatible; // true
|
|
715
|
+
result.methods.stringify.exists; // true
|
|
716
|
+
result.methods.parse.exists; // true
|
|
610
717
|
```
|
|
611
718
|
|
|
612
719
|
## detectKeyvEncryption(obj)
|
|
613
720
|
|
|
614
|
-
Returns a `KeyvEncryptionCapability`.
|
|
721
|
+
Returns a `KeyvEncryptionCapability`: `{ compatible, methods }`. `compatible` is `true` when both `encrypt` and `decrypt` methods are present.
|
|
615
722
|
|
|
616
723
|
```ts
|
|
617
724
|
import { detectKeyvEncryption } from 'keyv';
|
|
618
725
|
|
|
619
|
-
detectKeyvEncryption({ encrypt: (d) => d, decrypt: (d) => d });
|
|
620
|
-
//
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
## detectCapabilities(obj, spec)
|
|
624
|
-
|
|
625
|
-
A generic helper for building your own capability checks. Accepts a `CapabilitySpec` describing which methods and properties to look for, which are required, and the name of the composite boolean key.
|
|
626
|
-
|
|
627
|
-
```ts
|
|
628
|
-
import { detectCapabilities } from 'keyv';
|
|
629
|
-
|
|
630
|
-
const result = detectCapabilities(myObject, {
|
|
631
|
-
methods: ['read', 'write'],
|
|
632
|
-
properties: ['name'],
|
|
633
|
-
requiredKeys: ['read', 'write', 'name'],
|
|
634
|
-
compositeKey: 'isValid',
|
|
635
|
-
});
|
|
636
|
-
// { isValid: true/false, read: true/false, write: true/false, name: true/false }
|
|
726
|
+
const result = detectKeyvEncryption({ encrypt: (d) => d, decrypt: (d) => d });
|
|
727
|
+
result.compatible; // true
|
|
728
|
+
result.methods.encrypt.exists; // true
|
|
729
|
+
result.methods.decrypt.exists; // true
|
|
637
730
|
```
|
|
638
731
|
|
|
639
732
|
# API
|
|
@@ -699,6 +792,41 @@ Default: `new Map()`
|
|
|
699
792
|
|
|
700
793
|
The storage adapter instance to be used by Keyv.
|
|
701
794
|
|
|
795
|
+
## options.stats
|
|
796
|
+
|
|
797
|
+
Type: `Boolean`<br />
|
|
798
|
+
Default: `false`
|
|
799
|
+
|
|
800
|
+
Enable statistics tracking (hits, misses, sets, deletes, errors). See [.stats](#stats) for details.
|
|
801
|
+
|
|
802
|
+
## options.throwOnErrors
|
|
803
|
+
|
|
804
|
+
Type: `Boolean`<br />
|
|
805
|
+
Default: `false`
|
|
806
|
+
|
|
807
|
+
Throw on all errors instead of only when there are no `'error'` listeners. See [.throwOnErrors](#throwonerrors) for details.
|
|
808
|
+
|
|
809
|
+
## options.sanitize
|
|
810
|
+
|
|
811
|
+
Type: `KeyvSanitizeOptions`<br />
|
|
812
|
+
Default: `undefined`
|
|
813
|
+
|
|
814
|
+
Enable sanitization of keys and namespaces by stripping dangerous patterns. See [.sanitize](#sanitize) for details.
|
|
815
|
+
|
|
816
|
+
## options.encryption
|
|
817
|
+
|
|
818
|
+
Type: `KeyvEncryptionAdapter`<br />
|
|
819
|
+
Default: `undefined`
|
|
820
|
+
|
|
821
|
+
Encryption adapter used to encrypt and decrypt stored values. See [Encryption](#encryption) for details.
|
|
822
|
+
|
|
823
|
+
## options.checkExpired
|
|
824
|
+
|
|
825
|
+
Type: `Boolean`<br />
|
|
826
|
+
Default: `true`
|
|
827
|
+
|
|
828
|
+
When `true` (default), Keyv checks expiry at its own layer on `get`/`getMany`/`has`/`hasMany` in addition to the storage adapter. Set to `false` to trust the storage adapter alone. See [.checkExpired](#checkexpired) for details.
|
|
829
|
+
|
|
702
830
|
# Keyv Instance
|
|
703
831
|
|
|
704
832
|
Keys must always be strings. Values can be of any type.
|
|
@@ -715,13 +843,13 @@ Returns a promise which resolves to `true`.
|
|
|
715
843
|
|
|
716
844
|
Set multiple values using `KeyvEntry<Value>` objects (`{ key: string, value: Value, ttl?: number }`). The `Value` type is inferred from the entries provided.
|
|
717
845
|
|
|
718
|
-
## .get(key
|
|
846
|
+
## .get(key)
|
|
719
847
|
|
|
720
|
-
Returns a promise which resolves to the retrieved value.
|
|
848
|
+
Returns a promise which resolves to the retrieved value, or `undefined` if the key does not exist or is expired. If an array of keys is passed it delegates to `.getMany()` and resolves to an array of values.
|
|
721
849
|
|
|
722
|
-
## .getMany(keys
|
|
850
|
+
## .getMany(keys)
|
|
723
851
|
|
|
724
|
-
Returns a promise which resolves to an array of retrieved values.
|
|
852
|
+
Returns a promise which resolves to an array of retrieved values, with `undefined` for keys that do not exist or are expired.
|
|
725
853
|
|
|
726
854
|
## .getRaw(key)
|
|
727
855
|
|
|
@@ -832,7 +960,7 @@ for await (const [key, value] of keyv.iterator()) {
|
|
|
832
960
|
The iterator works with any storage backend:
|
|
833
961
|
- **Map stores**: iterates using the built-in `Symbol.iterator`
|
|
834
962
|
- **Storage adapters**: delegates to the adapter's `iterator()` method (e.g., Redis SCAN, SQL cursor)
|
|
835
|
-
- **Unsupported stores**:
|
|
963
|
+
- **Unsupported stores**: yields nothing if the store does not support iteration
|
|
836
964
|
|
|
837
965
|
# API - Properties
|
|
838
966
|
|
|
@@ -915,48 +1043,40 @@ keyv.compression = new KeyvGzip();
|
|
|
915
1043
|
console.log(keyv.compression); // KeyvGzip
|
|
916
1044
|
```
|
|
917
1045
|
|
|
918
|
-
## .
|
|
919
|
-
|
|
920
|
-
Type: `Boolean`<br />
|
|
921
|
-
Default: `true`
|
|
922
|
-
|
|
923
|
-
If set to `true` Keyv will prefix all keys with the namespace. This is useful if you want to avoid collisions with other data in your storage.
|
|
1046
|
+
## .encryption
|
|
924
1047
|
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
console.log(keyv.useKeyPrefix); // false
|
|
928
|
-
keyv.useKeyPrefix = true;
|
|
929
|
-
console.log(keyv.useKeyPrefix); // true
|
|
930
|
-
```
|
|
1048
|
+
Type: `KeyvEncryptionAdapter`<br />
|
|
1049
|
+
Default: `undefined`
|
|
931
1050
|
|
|
932
|
-
|
|
1051
|
+
The encryption adapter used to encrypt and decrypt stored values. If `undefined` (default) values are not encrypted. See [Encryption](#encryption) for more details.
|
|
933
1052
|
|
|
934
1053
|
```js
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
await keyv.set('foo', 'bar'); // true
|
|
944
|
-
await keyv.get('foo'); // 'bar'
|
|
945
|
-
await keyv.clear();
|
|
1054
|
+
const keyv = new Keyv();
|
|
1055
|
+
console.log(keyv.encryption); // undefined
|
|
1056
|
+
keyv.encryption = {
|
|
1057
|
+
encrypt: async (data) => Buffer.from(data).toString('base64'),
|
|
1058
|
+
decrypt: async (data) => Buffer.from(data, 'base64').toString('utf8'),
|
|
1059
|
+
};
|
|
1060
|
+
console.log(keyv.encryption); // the encryption adapter
|
|
946
1061
|
```
|
|
947
1062
|
|
|
948
|
-
## .
|
|
1063
|
+
## .checkExpired
|
|
949
1064
|
|
|
950
1065
|
Type: `Boolean`<br />
|
|
951
1066
|
Default: `true`
|
|
952
1067
|
|
|
953
|
-
|
|
1068
|
+
A read-only property (configured via the `checkExpired` constructor option). When `true` (the default), Keyv checks expiry at its own layer on `get`, `getMany`, `has`, and `hasMany`, deleting any expired entries it encounters. It does this using the absolute `expires` stored in the serialized envelope, so reads stay **millisecond-precise regardless of the adapter**.
|
|
1069
|
+
|
|
1070
|
+
This defaults to `true` because some backends can return entries that are already logically expired: Memcached's `exptime` is **second-granular** (a value can linger up to ~1s past a sub-second deadline), and DynamoDB's native TTL is a **background sweep that can lag by hours** before it deletes expired items. Trusting the backend alone would surface those stale reads; the Keyv-layer check closes that gap.
|
|
1071
|
+
|
|
1072
|
+
Set it to `false` to trust the storage adapter to handle expiry on its own. That skips the extra decode + expiry check on every read (and lets `has`/`hasMany` use the adapter's native existence check), at the cost of backend-granularity expiry.
|
|
954
1073
|
|
|
955
1074
|
```js
|
|
956
|
-
const keyv = new Keyv(
|
|
957
|
-
console.log(keyv.
|
|
958
|
-
|
|
959
|
-
|
|
1075
|
+
const keyv = new Keyv();
|
|
1076
|
+
console.log(keyv.checkExpired); // true (default)
|
|
1077
|
+
|
|
1078
|
+
const trusting = new Keyv({ checkExpired: false });
|
|
1079
|
+
console.log(trusting.checkExpired); // false
|
|
960
1080
|
```
|
|
961
1081
|
|
|
962
1082
|
## .throwOnErrors
|
|
@@ -1059,10 +1179,12 @@ const stats = new KeyvStats({ enabled: true, maxEntries: 500, emitter: keyv });
|
|
|
1059
1179
|
```
|
|
1060
1180
|
|
|
1061
1181
|
## .sanitize
|
|
1062
|
-
Type: `
|
|
1063
|
-
Default:
|
|
1182
|
+
Type: `KeyvSanitize` (configured via the `sanitize` option: `KeyvSanitizeOptions`)<br />
|
|
1183
|
+
Default: disabled
|
|
1064
1184
|
|
|
1065
|
-
|
|
1185
|
+
The `.sanitize` property is a `KeyvSanitize` adapter. It is configured through the `sanitize` constructor option (`true`, or a `KeyvSanitizeOptions` object) and disabled by default.
|
|
1186
|
+
|
|
1187
|
+
It detects and strips dangerous patterns from keys and namespaces to protect against SQL injection, MongoDB operator injection, path traversal, and control character attacks. Harmless characters like quotes, slashes, and dollar signs pass through unchanged — only dangerous *patterns* are stripped.
|
|
1066
1188
|
|
|
1067
1189
|
Results are cached in an LRU cache (10,000 entries) for fast repeated lookups.
|
|
1068
1190
|
|
|
@@ -1117,11 +1239,16 @@ const keyv = new Keyv({
|
|
|
1117
1239
|
});
|
|
1118
1240
|
```
|
|
1119
1241
|
|
|
1120
|
-
Change at runtime:
|
|
1242
|
+
Change at runtime by updating the options on the existing adapter, or by replacing it:
|
|
1121
1243
|
```js
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1244
|
+
import { KeyvSanitize } from 'keyv';
|
|
1245
|
+
|
|
1246
|
+
// Update options on the existing adapter
|
|
1247
|
+
keyv.sanitize.updateOptions({ keys: true, namespace: true }); // enable all
|
|
1248
|
+
keyv.sanitize.updateOptions({ keys: { sql: true, mongo: false } }); // granular
|
|
1249
|
+
|
|
1250
|
+
// Or replace the adapter entirely
|
|
1251
|
+
keyv.sanitize = new KeyvSanitize({ keys: true, namespace: true });
|
|
1125
1252
|
```
|
|
1126
1253
|
|
|
1127
1254
|
Sanitization is applied to all key-accepting methods: `get`, `set`, `delete`, `has`, `getMany`, `setMany`, `deleteMany`, `hasMany`, `getRaw`, `getManyRaw`, `setRaw`, and `setManyRaw`. Namespace sanitization is applied at construction and when the `namespace` setter is used.
|