keyv 6.0.0-rc.1 → 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 +90 -66
- package/dist/index.cjs +419 -241
- package/dist/index.d.cts +76 -55
- package/dist/index.d.mts +76 -55
- package/dist/index.mjs +419 -241
- package/package.json +7 -7
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,6 +33,7 @@ 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)
|
|
@@ -49,7 +50,6 @@ There are a few existing modules similar to Keyv, however Keyv is different beca
|
|
|
49
50
|
- [.serialization](#serialization-1)
|
|
50
51
|
- [.compression](#compression-1)
|
|
51
52
|
- [.encryption](#encryption-1)
|
|
52
|
-
- [.throwOnErrors](#throwonerrors)
|
|
53
53
|
- [.checkExpired](#checkexpired)
|
|
54
54
|
- [.stats](#stats)
|
|
55
55
|
- [.sanitize](#sanitize)
|
|
@@ -192,9 +192,16 @@ await users.get('foo'); // undefined
|
|
|
192
192
|
await cache.get('foo'); // 'cache'
|
|
193
193
|
```
|
|
194
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
|
+
|
|
195
202
|
# Events
|
|
196
203
|
|
|
197
|
-
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).
|
|
198
205
|
|
|
199
206
|
```js
|
|
200
207
|
const keyv = new Keyv();
|
|
@@ -214,6 +221,45 @@ keyv.on('clear', handleClear);
|
|
|
214
221
|
keyv.on('disconnect', handleDisconnect);
|
|
215
222
|
```
|
|
216
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
|
+
|
|
217
263
|
# Hooks
|
|
218
264
|
|
|
219
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:
|
|
@@ -364,7 +410,7 @@ When serialization, compression, and/or encryption are configured, Keyv applies
|
|
|
364
410
|
|
|
365
411
|
**On get:** store → decrypt (optional) → decompress (optional) → parse → value
|
|
366
412
|
|
|
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
|
|
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.
|
|
368
414
|
|
|
369
415
|
# Official Storage Adapters
|
|
370
416
|
|
|
@@ -411,7 +457,7 @@ const lru = new QuickLRU({ maxSize: 1000 });
|
|
|
411
457
|
const keyv = new Keyv({ store: lru });
|
|
412
458
|
```
|
|
413
459
|
|
|
414
|
-
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/
|
|
415
461
|
|
|
416
462
|
## Storage Adapter Contract (v6)
|
|
417
463
|
|
|
@@ -441,6 +487,8 @@ A v6 adapter declares `capabilities.expires === true` (the `keyvStorageCapabilit
|
|
|
441
487
|
|
|
442
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.
|
|
443
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
|
+
|
|
444
492
|
# Built-in Adapters: Memory and Bridge
|
|
445
493
|
|
|
446
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`:
|
|
@@ -451,7 +499,7 @@ Keyv ships with two storage adapters built directly into the core package. You r
|
|
|
451
499
|
|
|
452
500
|
It adds the pieces a raw `Map` does not have:
|
|
453
501
|
|
|
454
|
-
- **Namespace prefixing** — keys are prefixed with the `namespace` and `
|
|
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.
|
|
455
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.
|
|
456
504
|
- **Batch and iteration** — `getMany`, `setMany`, `hasMany`, `deleteMany`, and an async `iterator()` (when the store supports `entries()`).
|
|
457
505
|
- **v6 contract** — declares `capabilities.expires === true`, so Keyv hands it the absolute `expires` timestamp directly and trusts it to enforce expiry.
|
|
@@ -459,8 +507,8 @@ It adds the pieces a raw `Map` does not have:
|
|
|
459
507
|
```js
|
|
460
508
|
import Keyv, { KeyvMemoryAdapter } from 'keyv';
|
|
461
509
|
|
|
462
|
-
// Wrap any Map-like store.
|
|
463
|
-
//
|
|
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.
|
|
464
512
|
const keyv = new Keyv({ store: new KeyvMemoryAdapter(new Map()), namespace: 'cache' });
|
|
465
513
|
|
|
466
514
|
// Or wrap an LRU to bound memory usage
|
|
@@ -475,11 +523,13 @@ const cache = new Keyv({ store: new KeyvMemoryAdapter(new QuickLRU({ maxSize: 10
|
|
|
475
523
|
- a **legacy storage adapter** — a full async adapter that does *not* declare `capabilities.expires` (i.e. pre-v6 third-party adapters), or
|
|
476
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`.
|
|
477
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
|
+
|
|
478
528
|
This is why existing third-party adapters keep working unchanged on v6. The bridge:
|
|
479
529
|
|
|
480
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.
|
|
481
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.
|
|
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.
|
|
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.
|
|
483
533
|
- **Forwards errors** — re-emits `error` events from the wrapped store so connection failures surface on the Keyv instance.
|
|
484
534
|
|
|
485
535
|
```js
|
|
@@ -488,8 +538,8 @@ import Keyv, { KeyvBridgeAdapter } from 'keyv';
|
|
|
488
538
|
// Usually automatic — just pass the store:
|
|
489
539
|
const keyv = new Keyv({ store: myAsyncStore });
|
|
490
540
|
|
|
491
|
-
// ...which is equivalent to wrapping it explicitly.
|
|
492
|
-
//
|
|
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:
|
|
493
543
|
const explicit = new Keyv({ store: new KeyvBridgeAdapter(myAsyncStore), namespace: 'cache' });
|
|
494
544
|
```
|
|
495
545
|
|
|
@@ -553,7 +603,7 @@ For more details about BigMap, see the [@keyv/bigmap documentation](https://gith
|
|
|
553
603
|
|
|
554
604
|
# Compression
|
|
555
605
|
|
|
556
|
-
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.
|
|
557
607
|
|
|
558
608
|
```js
|
|
559
609
|
import Keyv from 'keyv';
|
|
@@ -587,23 +637,24 @@ Great! Keyv is designed to be easily extended. You can build your own compressio
|
|
|
587
637
|
|
|
588
638
|
```typescript
|
|
589
639
|
interface KeyvCompressionAdapter {
|
|
590
|
-
compress(value:
|
|
591
|
-
decompress(value:
|
|
640
|
+
compress(value: string): Promise<string>;
|
|
641
|
+
decompress(value: string): Promise<string>;
|
|
592
642
|
}
|
|
593
643
|
```
|
|
594
644
|
|
|
595
645
|
In addition to the interface, you can test it with our compression test suite using @keyv/test-suite:
|
|
596
646
|
|
|
597
647
|
```js
|
|
598
|
-
import {
|
|
648
|
+
import { compressionTestSuite } from '@keyv/test-suite';
|
|
649
|
+
import { it } from 'vitest';
|
|
599
650
|
import KeyvGzip from '@keyv/compress-gzip';
|
|
600
651
|
|
|
601
|
-
|
|
652
|
+
compressionTestSuite(it, new KeyvGzip());
|
|
602
653
|
```
|
|
603
654
|
|
|
604
655
|
# Encryption
|
|
605
656
|
|
|
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.
|
|
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.
|
|
607
658
|
|
|
608
659
|
```typescript
|
|
609
660
|
interface KeyvEncryptionAdapter {
|
|
@@ -669,6 +720,8 @@ Returns a `KeyvStorageCapability`: `{ compatible, store, methods }`. `compatible
|
|
|
669
720
|
- **`"asyncMap"`** — has at least async `get`, `set`, `delete`, and `clear`
|
|
670
721
|
- **`"none"`** — not a usable store
|
|
671
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
|
+
|
|
672
725
|
```ts
|
|
673
726
|
import { detectKeyvStorage } from 'keyv';
|
|
674
727
|
|
|
@@ -735,7 +788,7 @@ result.methods.decrypt.exists; // true
|
|
|
735
788
|
|
|
736
789
|
Returns a new Keyv instance.
|
|
737
790
|
|
|
738
|
-
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).
|
|
739
792
|
|
|
740
793
|
## storage-adapter
|
|
741
794
|
|
|
@@ -749,7 +802,7 @@ The storage adapter instance to be used by Keyv.
|
|
|
749
802
|
Type: `String`
|
|
750
803
|
Default: `undefined`
|
|
751
804
|
|
|
752
|
-
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.
|
|
753
806
|
|
|
754
807
|
## options
|
|
755
808
|
|
|
@@ -762,7 +815,7 @@ The options object is also passed through to the storage adapter. Check your sto
|
|
|
762
815
|
Type: `String`<br />
|
|
763
816
|
Default: `undefined`
|
|
764
817
|
|
|
765
|
-
Namespace for the current instance.
|
|
818
|
+
Namespace for the current instance. When omitted, Keyv uses the namespace set on the storage adapter, if any.
|
|
766
819
|
|
|
767
820
|
## options.ttl
|
|
768
821
|
|
|
@@ -799,13 +852,6 @@ Default: `false`
|
|
|
799
852
|
|
|
800
853
|
Enable statistics tracking (hits, misses, sets, deletes, errors). See [.stats](#stats) for details.
|
|
801
854
|
|
|
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
855
|
## options.sanitize
|
|
810
856
|
|
|
811
857
|
Type: `KeyvSanitizeOptions`<br />
|
|
@@ -835,7 +881,7 @@ Keys must always be strings. Values can be of any type.
|
|
|
835
881
|
|
|
836
882
|
Set a value.
|
|
837
883
|
|
|
838
|
-
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.
|
|
839
885
|
|
|
840
886
|
Returns a promise which resolves to `true`.
|
|
841
887
|
|
|
@@ -861,7 +907,7 @@ Returns a promise which resolves to an array of raw stored data for the keys or
|
|
|
861
907
|
|
|
862
908
|
## .setRaw(key, value)
|
|
863
909
|
|
|
864
|
-
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.
|
|
865
911
|
|
|
866
912
|
Returns a promise which resolves to `true`.
|
|
867
913
|
|
|
@@ -912,6 +958,8 @@ Delete all entries in the current namespace.
|
|
|
912
958
|
|
|
913
959
|
Returns a promise which is resolved when the entries have been cleared.
|
|
914
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
|
+
|
|
915
963
|
## .has(key)
|
|
916
964
|
|
|
917
965
|
Check if a key exists in the store.
|
|
@@ -968,7 +1016,7 @@ The iterator works with any storage backend:
|
|
|
968
1016
|
|
|
969
1017
|
Type: `String`
|
|
970
1018
|
|
|
971
|
-
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.
|
|
972
1020
|
|
|
973
1021
|
```js
|
|
974
1022
|
const keyv = new Keyv({ namespace: 'my-namespace' });
|
|
@@ -1079,34 +1127,6 @@ const trusting = new Keyv({ checkExpired: false });
|
|
|
1079
1127
|
console.log(trusting.checkExpired); // false
|
|
1080
1128
|
```
|
|
1081
1129
|
|
|
1082
|
-
## .throwOnErrors
|
|
1083
|
-
|
|
1084
|
-
Type: `Boolean`<br />
|
|
1085
|
-
Default: `false`
|
|
1086
|
-
|
|
1087
|
-
If set to `true`, Keyv will throw an error if any operation fails. This is useful if you want to ensure that all operations are successful and you want to handle errors.
|
|
1088
|
-
|
|
1089
|
-
```js
|
|
1090
|
-
const keyv = new Keyv({ throwOnErrors: true });
|
|
1091
|
-
console.log(keyv.throwOnErrors); // true
|
|
1092
|
-
keyv.throwOnErrors = false;
|
|
1093
|
-
console.log(keyv.throwOnErrors); // false
|
|
1094
|
-
```
|
|
1095
|
-
|
|
1096
|
-
A good example of this is with the `@keyv/redis` storage adapter. If you want to handle connection errors, retries, and timeouts more gracefully, you can use the `throwOnErrors` option. This will throw an error if any operation fails, allowing you to catch it and handle it accordingly:
|
|
1097
|
-
|
|
1098
|
-
```js
|
|
1099
|
-
import Keyv from 'keyv';
|
|
1100
|
-
import KeyvRedis from '@keyv/redis';
|
|
1101
|
-
|
|
1102
|
-
// create redis instance that will throw on connection error
|
|
1103
|
-
const keyvRedis = new KeyvRedis('redis://user:pass@localhost:6379', { throwOnConnectErrors: true });
|
|
1104
|
-
|
|
1105
|
-
const keyv = new Keyv({ store: keyvRedis, throwOnErrors: true });
|
|
1106
|
-
```
|
|
1107
|
-
|
|
1108
|
-
What this does is it only throw on connection errors with the Redis client.
|
|
1109
|
-
|
|
1110
1130
|
## .stats
|
|
1111
1131
|
Type: `KeyvStats`<br />
|
|
1112
1132
|
Default: `KeyvStats` instance with `enabled: false`
|
|
@@ -1123,7 +1143,7 @@ console.log(keyv.stats.enabled); // true
|
|
|
1123
1143
|
|
|
1124
1144
|
**Aggregate counters:**
|
|
1125
1145
|
- `hits`: Number of successful cache retrievals
|
|
1126
|
-
- `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.
|
|
1127
1147
|
- `sets`: Number of set operations
|
|
1128
1148
|
- `deletes`: Number of delete operations
|
|
1129
1149
|
- `errors`: Number of errors encountered
|
|
@@ -1182,9 +1202,9 @@ const stats = new KeyvStats({ enabled: true, maxEntries: 500, emitter: keyv });
|
|
|
1182
1202
|
Type: `KeyvSanitize` (configured via the `sanitize` option: `KeyvSanitizeOptions`)<br />
|
|
1183
1203
|
Default: disabled
|
|
1184
1204
|
|
|
1185
|
-
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.
|
|
1186
1206
|
|
|
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.
|
|
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`.
|
|
1188
1208
|
|
|
1189
1209
|
Results are cached in an LRU cache (10,000 entries) for fast repeated lookups.
|
|
1190
1210
|
|
|
@@ -1208,18 +1228,18 @@ Results are cached in an LRU cache (10,000 entries) for fast repeated lookups.
|
|
|
1208
1228
|
|
|
1209
1229
|
Enable all sanitization:
|
|
1210
1230
|
```js
|
|
1211
|
-
const keyv = new Keyv({ sanitize: true });
|
|
1212
|
-
await keyv.set("
|
|
1213
|
-
// 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"
|
|
1214
1234
|
|
|
1215
1235
|
// Harmless characters pass through
|
|
1216
1236
|
await keyv.set("user's-data", "value");
|
|
1217
1237
|
// Key is stored as "user's-data" (unchanged)
|
|
1218
1238
|
```
|
|
1219
1239
|
|
|
1220
|
-
Disable all sanitization (default)
|
|
1240
|
+
Disable all sanitization (default) by omitting `sanitize`, or by setting both targets to `false`:
|
|
1221
1241
|
```js
|
|
1222
|
-
const keyv = new Keyv({ sanitize: false });
|
|
1242
|
+
const keyv = new Keyv({ sanitize: { keys: false, namespace: false } });
|
|
1223
1243
|
```
|
|
1224
1244
|
|
|
1225
1245
|
Granular control per target and category:
|
|
@@ -1253,6 +1273,10 @@ keyv.sanitize = new KeyvSanitize({ keys: true, namespace: true });
|
|
|
1253
1273
|
|
|
1254
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.
|
|
1255
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
|
+
|
|
1256
1280
|
# Bun Support
|
|
1257
1281
|
|
|
1258
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).
|