keyv 6.0.0-beta.4 → 6.1.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 +149 -65
- package/dist/index.cjs +427 -246
- package/dist/index.d.cts +218 -125
- package/dist/index.d.mts +218 -125
- package/dist/index.mjs +427 -246
- package/package.json +9 -9
package/README.md
CHANGED
|
@@ -24,7 +24,7 @@ There are a few existing modules similar to Keyv, however Keyv is different beca
|
|
|
24
24
|
- Handles all JSON types plus `Buffer` and `BigInt` via the built-in `KeyvJsonSerializer`
|
|
25
25
|
- Supports namespaces
|
|
26
26
|
- Wide range of [**efficient, well tested**](#official-storage-adapters) storage adapters
|
|
27
|
-
- Connection errors are
|
|
27
|
+
- Connection errors are emitted as `error` events, so with a listener attached a database failure won't crash your app
|
|
28
28
|
- Supports the current active LTS version of Node.js or higher
|
|
29
29
|
|
|
30
30
|
# Table of Contents
|
|
@@ -33,10 +33,12 @@ There are a few existing modules similar to Keyv, however Keyv is different beca
|
|
|
33
33
|
- [Using Storage Adapters](#using-storage-adapters)
|
|
34
34
|
- [Namespaces](#namespaces)
|
|
35
35
|
- [Events](#events)
|
|
36
|
+
- [Error Handling](#error-handling)
|
|
36
37
|
- [Hooks](#hooks)
|
|
37
38
|
- [Serialization](#serialization)
|
|
38
39
|
- [Official Storage Adapters](#official-storage-adapters)
|
|
39
40
|
- [Third-party Storage Adapters](#third-party-storage-adapters)
|
|
41
|
+
- [Built-in Adapters: Memory and Bridge](#built-in-adapters-memory-and-bridge)
|
|
40
42
|
- [Using BigMap to Scale](#using-bigmap-to-scale)
|
|
41
43
|
- [Compression](#compression)
|
|
42
44
|
- [Capability Detection](#capability-detection)
|
|
@@ -48,7 +50,6 @@ There are a few existing modules similar to Keyv, however Keyv is different beca
|
|
|
48
50
|
- [.serialization](#serialization-1)
|
|
49
51
|
- [.compression](#compression-1)
|
|
50
52
|
- [.encryption](#encryption-1)
|
|
51
|
-
- [.throwOnErrors](#throwonerrors)
|
|
52
53
|
- [.checkExpired](#checkexpired)
|
|
53
54
|
- [.stats](#stats)
|
|
54
55
|
- [.sanitize](#sanitize)
|
|
@@ -191,9 +192,16 @@ await users.get('foo'); // undefined
|
|
|
191
192
|
await cache.get('foo'); // 'cache'
|
|
192
193
|
```
|
|
193
194
|
|
|
195
|
+
You can also set the namespace on the storage adapter. Keyv uses it when Keyv has no namespace of its own. When both are set, Keyv's namespace wins and is applied to the adapter.
|
|
196
|
+
|
|
197
|
+
```js
|
|
198
|
+
const users = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379', { namespace: 'users' }));
|
|
199
|
+
users.namespace; // 'users'
|
|
200
|
+
```
|
|
201
|
+
|
|
194
202
|
# Events
|
|
195
203
|
|
|
196
|
-
Keyv is an `EventEmitter` (built on [hookified](https://github.com/jaredwray/hookified)) and
|
|
204
|
+
Keyv is an `EventEmitter` (built on [hookified](https://github.com/jaredwray/hookified)) and emits an `'error'` event when an operation fails. Whether the operation also throws depends on whether a listener is attached. See [Error Handling](#error-handling).
|
|
197
205
|
|
|
198
206
|
```js
|
|
199
207
|
const keyv = new Keyv();
|
|
@@ -213,6 +221,45 @@ keyv.on('clear', handleClear);
|
|
|
213
221
|
keyv.on('disconnect', handleDisconnect);
|
|
214
222
|
```
|
|
215
223
|
|
|
224
|
+
# Error Handling
|
|
225
|
+
|
|
226
|
+
Keyv handles errors the way a Node.js `EventEmitter` does. When an operation fails, for example because the storage adapter cannot reach its database, Keyv emits an `'error'` event:
|
|
227
|
+
|
|
228
|
+
- **With an `'error'` listener attached**, the listener receives the error and the operation returns a fallback value instead of throwing.
|
|
229
|
+
- **With no `'error'` listener attached**, the operation rejects with the error.
|
|
230
|
+
|
|
231
|
+
```js
|
|
232
|
+
const keyv = new Keyv(store); // any storage adapter
|
|
233
|
+
|
|
234
|
+
// No listener yet: a failed call rejects.
|
|
235
|
+
try {
|
|
236
|
+
await keyv.get('foo');
|
|
237
|
+
} catch (error) {
|
|
238
|
+
console.error('get failed', error);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// With a listener: the listener gets the error and the call returns a fallback value.
|
|
242
|
+
keyv.on('error', (error) => console.error('Keyv error', error));
|
|
243
|
+
await keyv.get('foo'); // undefined if the store fails
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
These are the fallback values a failed call returns when a listener is attached:
|
|
247
|
+
|
|
248
|
+
| Method | Returns |
|
|
249
|
+
| --- | --- |
|
|
250
|
+
| `get`, `getRaw` | `undefined` |
|
|
251
|
+
| `getMany`, `getManyRaw` | an array of `undefined` |
|
|
252
|
+
| `set`, `setRaw`, `delete`, `has` | `false` |
|
|
253
|
+
| `setMany`, `setManyRaw`, `deleteMany`, `hasMany` | an array of `false` |
|
|
254
|
+
| `clear`, `disconnect` | `undefined` |
|
|
255
|
+
| `iterator` | ends the iteration |
|
|
256
|
+
|
|
257
|
+
A failed read looks the same as a missing key, so use the `'error'` events when you need to tell them apart. In [stats](#stats), a failed read counts as an error, not a miss.
|
|
258
|
+
|
|
259
|
+
Storage adapters can also emit `'error'` on their own, outside any Keyv call. The Redis client does this when a connection drops, for example. Keyv forwards these errors to its own `'error'` event, and the same rule applies: with no listener attached the error is thrown, and because no call is waiting for it, it can crash your process. Attach an `'error'` listener whenever you use a storage adapter that connects to a server.
|
|
260
|
+
|
|
261
|
+
Keyv v5's `throwOnErrors` and `emitErrors` options were removed in v6. See the [v5 to v6 migration guide](https://keyv.org/docs/migration/v5-to-v6/#error-handling-changed-and-throwonerrors-was-removed) for how v5 behaved and what to change.
|
|
262
|
+
|
|
216
263
|
# Hooks
|
|
217
264
|
|
|
218
265
|
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:
|
|
@@ -363,7 +410,7 @@ When serialization, compression, and/or encryption are configured, Keyv applies
|
|
|
363
410
|
|
|
364
411
|
**On get:** store → decrypt (optional) → decompress (optional) → parse → value
|
|
365
412
|
|
|
366
|
-
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
|
|
413
|
+
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 is skipped. Encryption isn't skipped: with an encryption adapter set, every write fails instead of storing the value unencrypted. Keyv emits `error`, and `set()` returns `false` when a listener is attached or rejects when none is.
|
|
367
414
|
|
|
368
415
|
# Official Storage Adapters
|
|
369
416
|
|
|
@@ -410,7 +457,7 @@ const lru = new QuickLRU({ maxSize: 1000 });
|
|
|
410
457
|
const keyv = new Keyv({ store: lru });
|
|
411
458
|
```
|
|
412
459
|
|
|
413
|
-
View the complete list of third-party storage adapters and learn how to build your own at https://keyv.org/docs/
|
|
460
|
+
View the complete list of third-party storage adapters and learn how to build your own at https://keyv.org/docs/storage-adapters/third-party/
|
|
414
461
|
|
|
415
462
|
## Storage Adapter Contract (v6)
|
|
416
463
|
|
|
@@ -436,9 +483,65 @@ class MyAdapter {
|
|
|
436
483
|
}
|
|
437
484
|
```
|
|
438
485
|
|
|
439
|
-
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`](#
|
|
486
|
+
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.
|
|
487
|
+
|
|
488
|
+
> **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.
|
|
489
|
+
|
|
490
|
+
> **Report each failure once.** When an operation fails, an adapter should either reject, and Keyv then emits the error, or emit `'error'` itself and return a fallback value. It should not do both: Keyv forwards the adapter's `'error'` events, so a failure that is emitted and then rejected reaches Keyv's listeners twice. Errors that happen outside any call, such as a dropped connection, should be emitted. See [Error Handling](#error-handling).
|
|
491
|
+
|
|
492
|
+
# Built-in Adapters: Memory and Bridge
|
|
493
|
+
|
|
494
|
+
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`:
|
|
495
|
+
|
|
496
|
+
## KeyvMemoryAdapter
|
|
497
|
+
|
|
498
|
+
`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`.
|
|
499
|
+
|
|
500
|
+
It adds the pieces a raw `Map` does not have:
|
|
501
|
+
|
|
502
|
+
- **Namespace prefixing** — keys are prefixed with the `namespace` and `namespaceSeparator` (default `::`), so one underlying store can host multiple namespaces. A namespaced `clear()` removes only the current namespace's keys, which it finds with the underlying store's `keys()` method (a standard `Map` has one). A minimal store without `keys()` can't tell namespaces apart, so a namespaced `clear()` throws instead of wiping the **entire** store; call `clear()` without a namespace to empty it.
|
|
503
|
+
- **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.
|
|
504
|
+
- **Batch and iteration** — `getMany`, `setMany`, `hasMany`, `deleteMany`, and an async `iterator()` (when the store supports `entries()`).
|
|
505
|
+
- **v6 contract** — declares `capabilities.expires === true`, so Keyv hands it the absolute `expires` timestamp directly and trusts it to enforce expiry.
|
|
506
|
+
|
|
507
|
+
```js
|
|
508
|
+
import Keyv, { KeyvMemoryAdapter } from 'keyv';
|
|
509
|
+
|
|
510
|
+
// Wrap any Map-like store. Set the namespace on Keyv or on the adapter. When both are set,
|
|
511
|
+
// Keyv's namespace wins and is applied to the adapter.
|
|
512
|
+
const keyv = new Keyv({ store: new KeyvMemoryAdapter(new Map()), namespace: 'cache' });
|
|
513
|
+
|
|
514
|
+
// Or wrap an LRU to bound memory usage
|
|
515
|
+
import QuickLRU from 'quick-lru';
|
|
516
|
+
const cache = new Keyv({ store: new KeyvMemoryAdapter(new QuickLRU({ maxSize: 1000 })) });
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
## KeyvBridgeAdapter
|
|
520
|
+
|
|
521
|
+
`KeyvBridgeAdapter` wraps any **promise-based / async store** and adapts it to the v6 storage contract. Keyv applies it automatically when you pass:
|
|
440
522
|
|
|
441
|
-
|
|
523
|
+
- a **legacy storage adapter** — a full async adapter that does *not* declare `capabilities.expires` (i.e. pre-v6 third-party adapters), or
|
|
524
|
+
- 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`.
|
|
525
|
+
|
|
526
|
+
A method that isn't a native `async` function can still return a promise, such as an `async` method compiled to an older target or one written without `async`. So when a store isn't a `Map` and its methods aren't native `async` functions, Keyv calls its `has` once when the store is set. If that returns a promise, the store goes through the bridge. Otherwise Keyv wraps it in `KeyvMemoryAdapter`.
|
|
527
|
+
|
|
528
|
+
This is why existing third-party adapters keep working unchanged on v6. The bridge:
|
|
529
|
+
|
|
530
|
+
- **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.
|
|
531
|
+
- **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.
|
|
532
|
+
- **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 (or keeps the store's own namespace when the bridge has none) 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. A namespaced `clear()` then finds the namespace's keys with the store's `iterator()`; a store without one can't tell namespaces apart, so `clear()` throws instead of wiping every namespace.
|
|
533
|
+
- **Forwards errors** — re-emits `error` events from the wrapped store so connection failures surface on the Keyv instance.
|
|
534
|
+
|
|
535
|
+
```js
|
|
536
|
+
import Keyv, { KeyvBridgeAdapter } from 'keyv';
|
|
537
|
+
|
|
538
|
+
// Usually automatic — just pass the store:
|
|
539
|
+
const keyv = new Keyv({ store: myAsyncStore });
|
|
540
|
+
|
|
541
|
+
// ...which is equivalent to wrapping it explicitly. A namespace on the Keyv options is applied
|
|
542
|
+
// to the adapter. Without one, Keyv keeps the adapter's own namespace:
|
|
543
|
+
const explicit = new Keyv({ store: new KeyvBridgeAdapter(myAsyncStore), namespace: 'cache' });
|
|
544
|
+
```
|
|
442
545
|
|
|
443
546
|
# Using BigMap to Scale
|
|
444
547
|
|
|
@@ -500,7 +603,7 @@ For more details about BigMap, see the [@keyv/bigmap documentation](https://gith
|
|
|
500
603
|
|
|
501
604
|
# Compression
|
|
502
605
|
|
|
503
|
-
Keyv supports `gzip`, `brotli` and `lz4` compression. To enable compression, pass the `
|
|
606
|
+
Keyv supports `gzip`, `brotli` and `lz4` compression. To enable compression, pass the `compression` option to the constructor. Compression runs on the serialized value, so it requires a serializer — the built-in `KeyvJsonSerializer` is enabled by default. With `serialization: false`, values are stored uncompressed.
|
|
504
607
|
|
|
505
608
|
```js
|
|
506
609
|
import Keyv from 'keyv';
|
|
@@ -534,23 +637,24 @@ Great! Keyv is designed to be easily extended. You can build your own compressio
|
|
|
534
637
|
|
|
535
638
|
```typescript
|
|
536
639
|
interface KeyvCompressionAdapter {
|
|
537
|
-
compress(value:
|
|
538
|
-
decompress(value:
|
|
640
|
+
compress(value: string): Promise<string>;
|
|
641
|
+
decompress(value: string): Promise<string>;
|
|
539
642
|
}
|
|
540
643
|
```
|
|
541
644
|
|
|
542
645
|
In addition to the interface, you can test it with our compression test suite using @keyv/test-suite:
|
|
543
646
|
|
|
544
647
|
```js
|
|
545
|
-
import {
|
|
648
|
+
import { compressionTestSuite } from '@keyv/test-suite';
|
|
649
|
+
import { it } from 'vitest';
|
|
546
650
|
import KeyvGzip from '@keyv/compress-gzip';
|
|
547
651
|
|
|
548
|
-
|
|
652
|
+
compressionTestSuite(it, new KeyvGzip());
|
|
549
653
|
```
|
|
550
654
|
|
|
551
655
|
# Encryption
|
|
552
656
|
|
|
553
|
-
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.
|
|
657
|
+
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. With `serialization: false`, writes fail with an error instead of storing values unencrypted.
|
|
554
658
|
|
|
555
659
|
```typescript
|
|
556
660
|
interface KeyvEncryptionAdapter {
|
|
@@ -616,6 +720,8 @@ Returns a `KeyvStorageCapability`: `{ compatible, store, methods }`. `compatible
|
|
|
616
720
|
- **`"asyncMap"`** — has at least async `get`, `set`, `delete`, and `clear`
|
|
617
721
|
- **`"none"`** — not a usable store
|
|
618
722
|
|
|
723
|
+
`methodType` is `"async"` only for native `async` functions, so a store whose methods return promises without being `async` is reported as `"mapLike"`. Keyv still sends such a store through [`KeyvBridgeAdapter`](#keyvbridgeadapter).
|
|
724
|
+
|
|
619
725
|
```ts
|
|
620
726
|
import { detectKeyvStorage } from 'keyv';
|
|
621
727
|
|
|
@@ -682,7 +788,7 @@ result.methods.decrypt.exists; // true
|
|
|
682
788
|
|
|
683
789
|
Returns a new Keyv instance.
|
|
684
790
|
|
|
685
|
-
The Keyv instance is also an `EventEmitter` that will emit an `'error'` event if the storage adapter connection fails.
|
|
791
|
+
The Keyv instance is also an `EventEmitter` that will emit an `'error'` event if an operation or the storage adapter connection fails. See [Error Handling](#error-handling).
|
|
686
792
|
|
|
687
793
|
## storage-adapter
|
|
688
794
|
|
|
@@ -696,7 +802,7 @@ The storage adapter instance to be used by Keyv.
|
|
|
696
802
|
Type: `String`
|
|
697
803
|
Default: `undefined`
|
|
698
804
|
|
|
699
|
-
This is the namespace for the current instance. When you set it
|
|
805
|
+
This is the namespace for the current instance. When you set it, Keyv also sets it on the storage adapter. When Keyv has no namespace of its own, this returns the namespace set on the storage adapter.
|
|
700
806
|
|
|
701
807
|
## options
|
|
702
808
|
|
|
@@ -709,7 +815,7 @@ The options object is also passed through to the storage adapter. Check your sto
|
|
|
709
815
|
Type: `String`<br />
|
|
710
816
|
Default: `undefined`
|
|
711
817
|
|
|
712
|
-
Namespace for the current instance.
|
|
818
|
+
Namespace for the current instance. When omitted, Keyv uses the namespace set on the storage adapter, if any.
|
|
713
819
|
|
|
714
820
|
## options.ttl
|
|
715
821
|
|
|
@@ -746,13 +852,6 @@ Default: `false`
|
|
|
746
852
|
|
|
747
853
|
Enable statistics tracking (hits, misses, sets, deletes, errors). See [.stats](#stats) for details.
|
|
748
854
|
|
|
749
|
-
## options.throwOnErrors
|
|
750
|
-
|
|
751
|
-
Type: `Boolean`<br />
|
|
752
|
-
Default: `false`
|
|
753
|
-
|
|
754
|
-
Throw on all errors instead of only when there are no `'error'` listeners. See [.throwOnErrors](#throwonerrors) for details.
|
|
755
|
-
|
|
756
855
|
## options.sanitize
|
|
757
856
|
|
|
758
857
|
Type: `KeyvSanitizeOptions`<br />
|
|
@@ -770,9 +869,9 @@ Encryption adapter used to encrypt and decrypt stored values. See [Encryption](#
|
|
|
770
869
|
## options.checkExpired
|
|
771
870
|
|
|
772
871
|
Type: `Boolean`<br />
|
|
773
|
-
Default: `
|
|
872
|
+
Default: `true`
|
|
774
873
|
|
|
775
|
-
When `true
|
|
874
|
+
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.
|
|
776
875
|
|
|
777
876
|
# Keyv Instance
|
|
778
877
|
|
|
@@ -782,7 +881,7 @@ Keys must always be strings. Values can be of any type.
|
|
|
782
881
|
|
|
783
882
|
Set a value.
|
|
784
883
|
|
|
785
|
-
By default keys are persistent. You can set an expiry TTL in milliseconds.
|
|
884
|
+
By default keys are persistent. You can set an expiry TTL in milliseconds. A fractional TTL is rounded up to a whole millisecond, since stores such as PostgreSQL and Redis only accept whole-millisecond expiry times.
|
|
786
885
|
|
|
787
886
|
Returns a promise which resolves to `true`.
|
|
788
887
|
|
|
@@ -808,7 +907,7 @@ Returns a promise which resolves to an array of raw stored data for the keys or
|
|
|
808
907
|
|
|
809
908
|
## .setRaw(key, value)
|
|
810
909
|
|
|
811
|
-
Sets a raw value in the store without wrapping. This is the write-side counterpart to `.getRaw()`. The caller provides the `KeyvValue` envelope directly (`{ value, expires? }`) instead of having Keyv wrap it. The envelope is still serialized before storing so that all read paths (`get()`, `getRaw()`, `has()`, `getManyRaw()`) work consistently. If you need TTL-based expiration, set `expires` on the value directly (e.g. `{ value: 'bar', expires: Date.now() + 60000 }`). The store-level TTL is derived automatically from `value.expires
|
|
910
|
+
Sets a raw value in the store without wrapping. This is the write-side counterpart to `.getRaw()`. The caller provides the `KeyvValue` envelope directly (`{ value, expires? }`) instead of having Keyv wrap it. The envelope is still serialized before storing so that all read paths (`get()`, `getRaw()`, `has()`, `getManyRaw()`) work consistently. If you need TTL-based expiration, set `expires` on the value directly (e.g. `{ value: 'bar', expires: Date.now() + 60000 }`). The store-level TTL is derived automatically from `value.expires`, rounded up to a whole millisecond. An `expires` that isn't a finite number gives no store-level expiry.
|
|
812
911
|
|
|
813
912
|
Returns a promise which resolves to `true`.
|
|
814
913
|
|
|
@@ -859,6 +958,8 @@ Delete all entries in the current namespace.
|
|
|
859
958
|
|
|
860
959
|
Returns a promise which is resolved when the entries have been cleared.
|
|
861
960
|
|
|
961
|
+
If the store can't limit the delete to the namespace, nothing is deleted and Keyv emits `error` instead. That happens with a `Map`-like store that has no `keys()`, and with an older async store that has no `iterator()` and doesn't manage its own namespace.
|
|
962
|
+
|
|
862
963
|
## .has(key)
|
|
863
964
|
|
|
864
965
|
Check if a key exists in the store.
|
|
@@ -915,7 +1016,7 @@ The iterator works with any storage backend:
|
|
|
915
1016
|
|
|
916
1017
|
Type: `String`
|
|
917
1018
|
|
|
918
|
-
The namespace for the current instance. This will define the namespace for the current instance and the storage adapter. If you set the namespace to `undefined` it will no longer do key prefixing.
|
|
1019
|
+
The namespace for the current instance. This will define the namespace for the current instance and the storage adapter. If you set the namespace to `undefined` it will no longer do key prefixing. When Keyv has no namespace of its own, it uses the namespace set on the storage adapter, and this property returns it.
|
|
919
1020
|
|
|
920
1021
|
```js
|
|
921
1022
|
const keyv = new Keyv({ namespace: 'my-namespace' });
|
|
@@ -1010,43 +1111,22 @@ console.log(keyv.encryption); // the encryption adapter
|
|
|
1010
1111
|
## .checkExpired
|
|
1011
1112
|
|
|
1012
1113
|
Type: `Boolean`<br />
|
|
1013
|
-
Default: `
|
|
1014
|
-
|
|
1015
|
-
A read-only property (configured via the `checkExpired` constructor option). When `true`, Keyv checks expiry at its own layer on `get`, `getMany`, `has`, and `hasMany`, deleting any expired entries it encounters. When `false` (default) it trusts the storage adapter to handle expiry.
|
|
1016
|
-
|
|
1017
|
-
```js
|
|
1018
|
-
const keyv = new Keyv({ checkExpired: true });
|
|
1019
|
-
console.log(keyv.checkExpired); // true
|
|
1020
|
-
```
|
|
1021
|
-
|
|
1022
|
-
## .throwOnErrors
|
|
1023
|
-
|
|
1024
|
-
Type: `Boolean`<br />
|
|
1025
|
-
Default: `false`
|
|
1114
|
+
Default: `true`
|
|
1026
1115
|
|
|
1027
|
-
|
|
1116
|
+
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**.
|
|
1028
1117
|
|
|
1029
|
-
|
|
1030
|
-
const keyv = new Keyv({ throwOnErrors: true });
|
|
1031
|
-
console.log(keyv.throwOnErrors); // true
|
|
1032
|
-
keyv.throwOnErrors = false;
|
|
1033
|
-
console.log(keyv.throwOnErrors); // false
|
|
1034
|
-
```
|
|
1118
|
+
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.
|
|
1035
1119
|
|
|
1036
|
-
|
|
1120
|
+
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.
|
|
1037
1121
|
|
|
1038
1122
|
```js
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
// create redis instance that will throw on connection error
|
|
1043
|
-
const keyvRedis = new KeyvRedis('redis://user:pass@localhost:6379', { throwOnConnectErrors: true });
|
|
1123
|
+
const keyv = new Keyv();
|
|
1124
|
+
console.log(keyv.checkExpired); // true (default)
|
|
1044
1125
|
|
|
1045
|
-
const
|
|
1126
|
+
const trusting = new Keyv({ checkExpired: false });
|
|
1127
|
+
console.log(trusting.checkExpired); // false
|
|
1046
1128
|
```
|
|
1047
1129
|
|
|
1048
|
-
What this does is it only throw on connection errors with the Redis client.
|
|
1049
|
-
|
|
1050
1130
|
## .stats
|
|
1051
1131
|
Type: `KeyvStats`<br />
|
|
1052
1132
|
Default: `KeyvStats` instance with `enabled: false`
|
|
@@ -1063,7 +1143,7 @@ console.log(keyv.stats.enabled); // true
|
|
|
1063
1143
|
|
|
1064
1144
|
**Aggregate counters:**
|
|
1065
1145
|
- `hits`: Number of successful cache retrievals
|
|
1066
|
-
- `misses`: Number of
|
|
1146
|
+
- `misses`: Number of reads that found no value because the key was missing or expired. A read that fails counts in `errors` instead.
|
|
1067
1147
|
- `sets`: Number of set operations
|
|
1068
1148
|
- `deletes`: Number of delete operations
|
|
1069
1149
|
- `errors`: Number of errors encountered
|
|
@@ -1122,9 +1202,9 @@ const stats = new KeyvStats({ enabled: true, maxEntries: 500, emitter: keyv });
|
|
|
1122
1202
|
Type: `KeyvSanitize` (configured via the `sanitize` option: `KeyvSanitizeOptions`)<br />
|
|
1123
1203
|
Default: disabled
|
|
1124
1204
|
|
|
1125
|
-
The `.sanitize` property is a `KeyvSanitize` adapter. It is configured through the `sanitize` constructor option
|
|
1205
|
+
The `.sanitize` property is a `KeyvSanitize` adapter. It is configured through the `sanitize` constructor option, a `KeyvSanitizeOptions` object, and is disabled by default.
|
|
1126
1206
|
|
|
1127
|
-
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.
|
|
1207
|
+
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. Stripping repeats until nothing matches, so `..././etc` becomes `etc` rather than `../etc`.
|
|
1128
1208
|
|
|
1129
1209
|
Results are cached in an LRU cache (10,000 entries) for fast repeated lookups.
|
|
1130
1210
|
|
|
@@ -1148,18 +1228,18 @@ Results are cached in an LRU cache (10,000 entries) for fast repeated lookups.
|
|
|
1148
1228
|
|
|
1149
1229
|
Enable all sanitization:
|
|
1150
1230
|
```js
|
|
1151
|
-
const keyv = new Keyv({ sanitize: true });
|
|
1152
|
-
await keyv.set("
|
|
1153
|
-
// Key is stored as "
|
|
1231
|
+
const keyv = new Keyv({ sanitize: { keys: true, namespace: true } });
|
|
1232
|
+
await keyv.set("user;1--", "value");
|
|
1233
|
+
// Key is stored as "user1"
|
|
1154
1234
|
|
|
1155
1235
|
// Harmless characters pass through
|
|
1156
1236
|
await keyv.set("user's-data", "value");
|
|
1157
1237
|
// Key is stored as "user's-data" (unchanged)
|
|
1158
1238
|
```
|
|
1159
1239
|
|
|
1160
|
-
Disable all sanitization (default)
|
|
1240
|
+
Disable all sanitization (default) by omitting `sanitize`, or by setting both targets to `false`:
|
|
1161
1241
|
```js
|
|
1162
|
-
const keyv = new Keyv({ sanitize: false });
|
|
1242
|
+
const keyv = new Keyv({ sanitize: { keys: false, namespace: false } });
|
|
1163
1243
|
```
|
|
1164
1244
|
|
|
1165
1245
|
Granular control per target and category:
|
|
@@ -1193,6 +1273,10 @@ keyv.sanitize = new KeyvSanitize({ keys: true, namespace: true });
|
|
|
1193
1273
|
|
|
1194
1274
|
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.
|
|
1195
1275
|
|
|
1276
|
+
A key that is empty after sanitization never reaches the store. `get` and `getRaw` return `undefined`, `set`, `setRaw`, `delete`, and `has` return `false`, and the batch methods put `undefined` or `false` in that key's position.
|
|
1277
|
+
|
|
1278
|
+
A namespace that is empty after sanitization, such as `$$` or `;`, becomes `keyv-sanitized`. An empty namespace would turn namespacing off, mixing the instance's keys with unrelated ones and letting `clear()` remove them.
|
|
1279
|
+
|
|
1196
1280
|
# Bun Support
|
|
1197
1281
|
|
|
1198
1282
|
We make a best effort to support [Bun](https://bun.sh/) as a runtime. Our default and primary target is Node.js, but we run tests against Bun to ensure compatibility. If you encounter any issues while using Keyv with Bun, please report them at our [GitHub issues](https://github.com/jaredwray/keyv/issues).
|