-
Notifications
You must be signed in to change notification settings - Fork 5
/
toolbox.ts
1475 lines (1442 loc) Β· 49.9 KB
/
toolbox.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* # KV Toolbox
*
* Provides a toolbox for interacting with a Deno KV store, including the
* ability to store values in an encrypted fashion. The main module exports a
* {@linkcode ToolboxKv} class that augments the Deno KV store with additional
* functionality. It also exports a {@linkcode CryptoToolboxKv} class that
* augments the Deno KV store with additional functionality for encrypting and
* decrypting blob values.
*
* Typically though, you would use the {@linkcode openKvToolbox} function to
* create an instance of the toolbox. If you pass in an encryption key, it will
* create an instance of the {@linkcode CryptoToolboxKv} class, otherwise it
* will create an instance of the {@linkcode ToolboxKv} class.
*
* The {@linkcode generateKey} function is exported and can be used to generate
* a random encryption key to use with the {@linkcode CryptoToolboxKv} class.
*
* ## Creating a toolbox
*
* To create an instance, you can use the {@linkcode openKvToolbox} function.
* It is similar to {@linkcode Deno.openKv} but returns an instance of the
* {@linkcode ToolboxKv} class:
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* ```
*
* ## Creating an encrypted toolbox
*
* To create an instance of the {@linkcode CryptoToolboxKv} class, you can pass
* in an encryption key:
*
* ```ts
* import { openKvToolbox, generateKey } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox({ encryptWith: generateKey() });
* ```
*
* > [!NOTE]
* > The encryption key should be kept secret and not shared with others. It
* > also needs to be stored securely, as it is required to decrypt values. The
* > above example generates a random encryption key, that will be lost when the
* > script is run again.
*
* ## Additional Modules
*
* This is the default module for the entire toolbox, and the individual
* capabilities of the toolbox are provided by additional exports of the
* library:
*
* - [batched_atomic](https://jsr.io/@kitsonk/kv-toolbox/doc/batched_atomic) - Provides a way to perform
* atomic operations in batches while working around the limitations of
* Deno KV.
* - [blob](https://jsr.io/@kitsonk/kv-toolbox/doc/blob) - Provides a way to store arbitrarily large binary
* data in Deno KV.
* - [crypto](https://jsr.io/@kitsonk/kv-toolbox/doc/crypto) - Provides a way to encrypt and decrypt data in
* Deno KV.
* - [json](https://jsr.io/@kitsonk/kv-toolbox/doc/json) - Provides utilities for handling Deno KV entries,
* keys, and values as structures which can be serialized and deserialized to
* JSON.
* - [keys](https://jsr.io/@kitsonk/kv-toolbox/doc/keys) - Provides convenience functions for working with
* keys in Deno KV.
* - [ndjson](https://jsr.io/@kitsonk/kv-toolbox/doc/ndjson) - Utilities for handling NDJSON which is a method
* for encoding JSON in a way that supports streaming, where each JSON entity
* is separated with a newline.
* - [size_of](https://jsr.io/@kitsonk/kv-toolbox/doc/size_of) - Provides a way to calculate the size of a
* JavaScript object in bytes.
*
* @module
*/
import {
type BatchAtomicOptions,
batchedAtomic,
type BatchedAtomicOperation,
} from "./batched_atomic.ts";
import {
type BlobJSON,
type BlobMeta,
get,
getAsBlob,
getAsJSON,
getAsResponse,
getMeta,
set,
} from "./blob.ts";
import { removeBlob } from "./blob_util.ts";
import { CryptoKv, type Encryptor } from "./crypto.ts";
import {
keys,
type KeyTree,
tree,
unique,
uniqueCount,
type UniqueCountElement,
} from "./keys.ts";
import {
exportEntries,
type ExportEntriesOptionsBytes,
type ExportEntriesOptionsJSON,
exportToResponse,
importEntries,
type ImportEntriesOptions,
type ImportEntriesResult,
} from "./ndjson.ts";
export { generateKey } from "./crypto.ts";
export { sizeOf } from "./size_of.ts";
/**
* A toolbox for interacting with a Deno KV store.
*
* It matches the Deno KV API, but adds additional functionality like the
* ability to manage arbitrary binary data, and the ability to batch import and
* export data in NDJSON format as well as other convenience functions.
*/
export class KvToolbox implements Disposable {
#kv: Deno.Kv;
constructor(kv: Deno.Kv) {
this.#kv = kv;
}
/**
* Similar to {@linkcode Deno.Kv.prototype.atomic} but deals with the limits
* of transactions imposed by Deno KV.
*
* When committing the transaction, the operation is broken up in batches and
* each commit result from each batch is returned, unless there is a commit
* error, where any pending batched operations will be abandoned and the last
* item in the commit result array will be the error.
*/
atomic(options?: BatchAtomicOptions): BatchedAtomicOperation {
return batchedAtomic(this.#kv, options);
}
/**
* Close the database connection. This will prevent any further operations
* from being performed on the database, and interrupt any in-flight
* operations immediately.
*/
close(): void {
return this.#kv.close();
}
/**
* Get a symbol that represents the versionstamp of the current atomic
* operation. This symbol can be used as the last part of a key in
* `.set()`, both directly on the `Kv` object and on an `AtomicOperation`
* object created from this `Kv` instance.
*/
commitVersionstamp(): symbol {
return this.#kv.commitVersionstamp();
}
/**
* Resolves with an array of unique sub keys/prefixes for the provided prefix
* along with the number of sub keys that match that prefix. The `count`
* represents the number of sub keys, a value of `0` indicates that only the
* exact key exists with no sub keys.
*
* This is useful when storing keys and values in a hierarchical/tree view,
* where you are retrieving a list including counts and you want to know all
* the unique _descendants_ of a key in order to be able to enumerate them.
*
* If you omit a `prefix`, all unique root keys are resolved.
*
* @example Getting a count of keys
*
* If you had the following keys stored in a datastore:
*
* ```ts
* ["a", "b"]
* ["a", "b", "c"]
* ["a", "d", "e"]
* ["a", "d", "f"]
* ```
*
* And you would get the following results when using `uniqueCount()`:
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* console.log(await kv.count(["a"]));
* // { key: ["a", "b"], count: 1 }
* // { key: ["a", "d"], count: 2 }
* await kv.close();
* ```
*/
counts(
prefix?: Deno.KvKey,
options?: Deno.KvListOptions,
): Promise<UniqueCountElement[]> {
return uniqueCount(this.#kv, prefix, options);
}
/**
* Delete the value for the given key from the database. If no value exists
* for the key, this operation is a no-op.
*
* Optionally, the `blob` option can be set to `true` to delete a value that
* has been set with `.setBlob()`.
*
* @example Deleting a value
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* await kv.delete(["foo"]);
* ```
*
* @example Deleting a blob value
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* await kv.delete(["foo"], { blob: true });
* ```
*/
delete(key: Deno.KvKey, options: { blob?: boolean } = {}): Promise<void> {
return options.blob ? removeBlob(this.#kv, key) : this.#kv.delete(key);
}
/**
* Add a value into the database queue to be delivered to the queue
* listener via {@linkcode Deno.Kv.listenQueue}.
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* await kv.enqueue("bar");
* ```
*
* The `delay` option can be used to specify the delay (in milliseconds)
* of the value delivery. The default delay is 0, which means immediate
* delivery.
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* await kv.enqueue("bar", { delay: 60000 });
* ```
*
* The `keysIfUndelivered` option can be used to specify the keys to
* be set if the value is not successfully delivered to the queue
* listener after several attempts. The values are set to the value of
* the queued message.
*
* The `backoffSchedule` option can be used to specify the retry policy for
* failed message delivery. Each element in the array represents the number of
* milliseconds to wait before retrying the delivery. For example,
* `[1000, 5000, 10000]` means that a failed delivery will be retried
* at most 3 times, with 1 second, 5 seconds, and 10 seconds delay
* between each retry.
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* await kv.enqueue("bar", {
* keysIfUndelivered: [["foo", "bar"]],
* backoffSchedule: [1000, 5000, 10000],
* });
* ```
*/
enqueue(
value: unknown,
options?: {
delay?: number;
keysIfUndelivered?: Deno.KvKey[];
backoffSchedule?: number[];
},
): Promise<Deno.KvCommitResult> {
return this.#kv.enqueue(value, options);
}
/**
* Like {@linkcode Deno.Kv} `.list()` method, but returns a
* {@linkcode Response} which will have a body that will be the exported
* entries that match the selector.
*
* The response will contain the appropriate content type and the `filename`
* option can be used to set the content disposition header so the client
* understands a file is being downloaded.
*/
export(
selector: Deno.KvListSelector,
options: {
close?: boolean;
response: true;
/**
* If provided, the response will include a header that indicates the file is
* meant to be downloaded (`Content-Disposition`). The extension `.ndjson`
* will be appended to the filename.
*/
filename?: string;
},
): Response;
/**
* Like {@linkcode Deno.Kv} `.list()` method, but returns a
* {@linkcode ReadableStream} where entries are converted to a JSON structure.
*
* This is ideal for streaming ndjson as part of a response.
*/
export(
selector: Deno.KvListSelector,
options: ExportEntriesOptionsJSON,
): ReadableStream<string>;
/**
* Like {@linkcode Deno.Kv} `.list()` method, but returns a
* {@linkcode ReadableStream} where entries are already converted to their raw
* byte representation after being encoded as JSON.
*
* This is ideal for streaming ndjson as part of a response.
*/
export(
selector: Deno.KvListSelector,
options?: ExportEntriesOptionsBytes,
): ReadableStream<Uint8Array>;
export(
selector: Deno.KvListSelector,
options:
| { close?: boolean; response: true; filename?: string }
| (
| ExportEntriesOptionsJSON
| ExportEntriesOptionsBytes
)
& { response?: boolean | undefined } = {},
): Response | ReadableStream<string | Uint8Array> {
return options.response
? exportToResponse(this.#kv, selector, options)
: exportEntries(this.#kv, selector, options);
}
/**
* Retrieve the value and versionstamp for the given key from the database
* in the form of a {@linkcode Deno.KvEntryMaybe}. If no value exists for
* the key, the returned entry will have a `null` value and versionstamp.
*
* The `consistency` option can be used to specify the consistency level
* for the read operation. The default consistency level is "strong". Some
* use cases can benefit from using a weaker consistency level. For more
* information on consistency levels, see the documentation for
* {@linkcode Deno.KvConsistencyLevel}.
*
* @example Getting a value
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const result = await kv.get(["foo"]);
* result.key; // ["foo"]
* result.value; // "bar"
* result.versionstamp; // "00000000000000010000"
* ```
*/
get<T = unknown>(
key: Deno.KvKey,
options?: { consistency?: Deno.KvConsistencyLevel },
): Promise<Deno.KvEntryMaybe<T>> {
return this.#kv.get(key, options);
}
/**
* Retrieve a binary object from the store as a {@linkcode Response} that has
* been previously {@linkcode set}. This will read the blob out of the KV
* store as a stream and set information in the response based on what is
* available from the source.
*
* If there are other headers required, they can be supplied in the options.
*
* Setting the `contentDisposition` to `true` will cause the function to
* resolve with a {@linkcode Response} which has the `Content-Disposition` set
* as an attachment with an appropriate file name. This is designed to send a
* response that instructs the browser to attempt to download the requested
* entry.
*
* If the blob entry is not present, the response will be set to a
* `404 Not Found` with a `null` body. The not found body and headers can be
* set in the options.
*
* @example Serving static content from Deno KV
*
* Creates a simple web server where the content has already been set in the
* Deno KV datastore as `Blob`s. This is a silly example just to show
* functionality and would be terribly inefficient in production:
*
* ```ts
* import { openKvToolbox } from "jsr:/@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
*
* const server = Deno.serve((req) => {
* const key = new URL(req.url)
* .pathname
* .slice(1)
* .split("/");
* key[key.length - 1] = key[key.length - 1] || "index.html";
* return kv.getAsBlob(key, { response: true });
* });
*
* server.finished.then(() => kv.close());
* ```
*/
getAsBlob(
key: Deno.KvKey,
options: {
consistency?: Deno.KvConsistencyLevel | undefined;
response: true;
/**
* Set an appropriate content disposition header on the response. This will
* cause a browser to usually treat the response as a download.
*
* If a filename is available, it will be used, otherwise a filename and
* extension derived from the key and content type.
*/
contentDisposition?: boolean | undefined;
/** Any headers init to be used in conjunction with creating the request. */
headers?: HeadersInit | undefined;
/** If the blob entry is not present, utilize this body when responding. This
* defaults to `null`. */
notFoundBody?: BodyInit | undefined;
/** If the blob entry is not present, utilize this headers init when
* responding. */
notFoundHeaders?: HeadersInit | undefined;
},
): Promise<Response>;
/**
* Retrieve a binary object from the store as {@linkcode BlobJSON} that has
* been previously {@linkcode set}.
*
* If there is no corresponding entry, the function will resolve to `null`.
*
* @example Getting a value
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const json = await kv.getAsBlob(["hello"], { json: true });
* // do something with blob json
* await kv.close();
* ```
*/
getAsBlob(
key: Deno.KvKey,
options: {
consistency?: Deno.KvConsistencyLevel | undefined;
json: true;
},
): Promise<BlobJSON | null>;
/**
* Retrieve a binary object from the store as a {@linkcode Blob},
* {@linkcode File}, {@linkcode BlobJSON} or {@linkcode Response} that has
* been previously {@linkcode set}.
*
* If the object set was originally a {@linkcode Blob} or {@linkcode File} the
* function will resolve with an instance of {@linkcode Blob} or
* {@linkcode File} with the same properties as the original.
*
* If it was some other form of binary data, it will be an instance of
* {@linkcode Blob} with an empty `.type` property.
*
* If there is no corresponding entry, the function will resolve to `null`.
*
* @example Getting a value
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const blob = await kv.getAsBlob(["hello"]);
* // do something with blob
* await kv.close();
* ```
*/
getAsBlob(
key: Deno.KvKey,
options?: {
consistency?: Deno.KvConsistencyLevel | undefined;
response?: boolean | undefined;
json?: boolean | undefined;
},
): Promise<Blob | File | null>;
getAsBlob(
key: Deno.KvKey,
options?: {
consistency?: Deno.KvConsistencyLevel | undefined;
response?: boolean | undefined;
contentDisposition?: boolean | undefined;
headers?: HeadersInit | undefined;
notFoundBody?: BodyInit | undefined;
notFoundHeaders?: HeadersInit | undefined;
json?: boolean | undefined;
},
): Promise<Blob | File | BlobJSON | Response | null> {
return options?.response
? options?.json
? getAsJSON(this.#kv, key, options)
: getAsResponse(this.#kv, key, options)
: getAsBlob(this.#kv, key, options);
}
/**
* Retrieve a binary object entry from the store with a given key that has
* been set with `.setBlob()`.
*
* When setting the option `stream` to `true`, a {@linkcode Deno.KvEntryMaybe}
* is resolved with a value of {@linkcode ReadableStream} to read the blob in
* chunks of {@linkcode Uint8Array}.
*
* When setting the option `blob` to `true`, the promise resolves with a
* {@linkcode Deno.KvEntryMaybe} with a value of {@linkcode Blob} or
* {@linkcode File}. If the original file had been a {@linkcode File} or
* {@linkcode Blob} it the resolved value will reflect that original value
* including its properties. If it was not, it will be a {@linkcode Blob} with
* a type of `""`.
*
* Otherwise the function resolves with a {@linkcode Deno.KvEntryMaybe} with a
* value of {@linkcode Uint8Array}.
*
* @example
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const stream = await kv.getBlob(["hello"], { stream: true });
* for await (const chunk of stream) {
* // do something with chunk
* }
* await kv.close();
* ```
*/
getBlob(
key: Deno.KvKey,
options: {
consistency?: Deno.KvConsistencyLevel | undefined;
stream: true;
},
): Promise<Deno.KvEntryMaybe<ReadableStream<Uint8Array>>>;
/**
* Retrieve a binary object from the store with a given key that has been
* set with `.setBlob()`.
*
* When setting the option `stream` to `true`, a {@linkcode ReadableStream} is
* returned to read the blob in chunks of {@linkcode Uint8Array}.
*
* When setting the option `blob` to `true`, the promise resolves with a
* {@linkcode Blob}, {@linkcode File}, or `null`. If the original file had
* been a {@linkcode File} or {@linkcode Blob} it the resolved value will
* reflect that original value including its properties. If it was not, it
* will be a {@linkcode Blob} with a type of `""`.
*
* Otherwise the function resolves with a single {@linkcode Uint8Array} or
* `null`.
*
* @example
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const blob = await kv.getBlob(["hello"], { blob: true });
* // do something with blob
* await kv.close();
* ```
*/
getBlob(
key: Deno.KvKey,
options: { consistency?: Deno.KvConsistencyLevel | undefined; blob: true },
): Promise<Deno.KvEntryMaybe<Blob | File>>;
/**
* Retrieve a binary object from the store with a given key that has been
* set with `.setBlob()`.
*
* When setting the option `stream` to `true`, a {@linkcode ReadableStream} is
* returned to read the blob in chunks of {@linkcode Uint8Array}
*
* When setting the option `blob` to `true`, the promise resolves with a
* {@linkcode Blob}, {@linkcode File}, or `null`. If the original file had
* been a {@linkcode File} or {@linkcode Blob} it the resolved value will
* reflect that original value including its properties. If it was not, it
* will be a {@linkcode Blob} with a type of `""`.
*
* Otherwise the function resolves with a single {@linkcode Uint8Array} or
* `null`.
*
* @example
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const blob = await kv.getBlob(["hello"]);
* // do something with ab
* await kv.close();
* ```
*/
getBlob(
key: Deno.KvKey,
options?: {
consistency?: Deno.KvConsistencyLevel | undefined;
blob?: boolean;
stream?: boolean;
},
): Promise<Deno.KvEntryMaybe<Uint8Array>>;
getBlob(key: Deno.KvKey, options?: {
consistency?: Deno.KvConsistencyLevel | undefined;
blob?: boolean;
stream?: boolean;
}): Promise<
Deno.KvEntryMaybe<ReadableStream<Uint8Array> | Uint8Array | File | Blob>
> {
return get(this.#kv, key, options);
}
/**
* Retrieve multiple values and versionstamps from the database in the form
* of an array of {@linkcode Deno.KvEntryMaybe} objects. The returned array
* will have the same length as the `keys` array, and the entries will be in
* the same order as the keys. If no value exists for a given key, the
* returned entry will have a `null` value and versionstamp.
*
* The `consistency` option can be used to specify the consistency level
* for the read operation. The default consistency level is "strong". Some
* use cases can benefit from using a weaker consistency level. For more
* information on consistency levels, see the documentation for
* {@linkcode Deno.KvConsistencyLevel}.
*
* @example Getting multiple values
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const result = await kv.getMany([["foo"], ["baz"]]);
* result[0].key; // ["foo"]
* result[0].value; // "bar"
* result[0].versionstamp; // "00000000000000010000"
* result[1].key; // ["baz"]
* result[1].value; // null
* result[1].versionstamp; // null
* ```
*/
getMany<T extends readonly unknown[]>(
keys: readonly [...{ [K in keyof T]: Deno.KvKey }],
options?: { consistency?: Deno.KvConsistencyLevel },
): Promise<{ [K in keyof T]: Deno.KvEntryMaybe<T[K]> }> {
return this.#kv.getMany(keys, options);
}
/**
* Retrieve a binary object's meta data from the store as a
* {@linkcode Deno.KvEntryMaybe}.
*
* @example Getting meta data
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const maybeMeta = await kv.getMeta(["hello"]));
* await kv.close();
* ```
*/
getMeta(
key: Deno.KvKey,
options?: { consistency?: Deno.KvConsistencyLevel | undefined },
): Promise<Deno.KvEntryMaybe<BlobMeta>> {
return getMeta(this.#kv, key, options);
}
/**
* Allows NDJSON to be imported in a target {@linkcode Deno.Kv}.
*
* The `data` can be in multiple forms, including {@linkcode ReadableStream},
* {@linkcode Blob}, {@linkcode File}, {@linkcode ArrayBuffer}, typed array,
* or string.
*/
import(
data:
| ReadableStream<Uint8Array>
| Blob
| ArrayBufferView
| ArrayBuffer
| string,
options?: ImportEntriesOptions,
): Promise<ImportEntriesResult> {
return importEntries(this.#kv, data, options);
}
/**
* Retrieve a list of keys in the database. The returned list is an
* {@linkcode Deno.KvListIterator} which can be used to iterate over the
* entries in the database.
*
* Each list operation must specify a selector which is used to specify the
* range of keys to return. The selector can either be a prefix selector, or
* a range selector:
*
* - A prefix selector selects all keys that start with the given prefix of
* key parts. For example, the selector `["users"]` will select all keys
* that start with the prefix `["users"]`, such as `["users", "alice"]`
* and `["users", "bob"]`. Note that you can not partially match a key
* part, so the selector `["users", "a"]` will not match the key
* `["users", "alice"]`. A prefix selector may specify a `start` key that
* is used to skip over keys that are lexicographically less than the
* start key.
* - A range selector selects all keys that are lexicographically between
* the given start and end keys (including the start, and excluding the
* end). For example, the selector `["users", "a"], ["users", "n"]` will
* select all keys that start with the prefix `["users"]` and have a
* second key part that is lexicographically between `a` and `n`, such as
* `["users", "alice"]`, `["users", "bob"]`, and `["users", "mike"]`, but
* not `["users", "noa"]` or `["users", "zoe"]`.
*
* The `options` argument can be used to specify additional options for the
* list operation. See the documentation for {@linkcode Deno.KvListOptions}
* for more information.
*
* @example Iterating over a list of entries
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const entries = kv.list({ prefix: ["users"] });
* for await (const entry of entries) {
* entry.key; // ["users", "alice"]
* entry.value; // { name: "Alice" }
* entry.versionstamp; // "00000000000000010000"
* }
* ```
*/
list<T = unknown>(
selector: Deno.KvListSelector,
options?: Deno.KvListOptions,
): Deno.KvListIterator<T> {
return this.#kv.list<T>(selector, options);
}
/**
* Listen for queue values to be delivered from the database queue, which
* were enqueued with {@linkcode Deno.Kv.enqueue}. The provided handler
* callback is invoked on every dequeued value. A failed callback
* invocation is automatically retried multiple times until it succeeds
* or until the maximum number of retries is reached.
*
* @example Listening for queue values
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* kv.listenQueue(async (msg: unknown) => {
* await kv.set(["foo"], msg);
* });
* ```
*/
// deno-lint-ignore no-explicit-any
listenQueue(handler: (value: any) => Promise<void> | void): Promise<void> {
return this.#kv.listenQueue(handler);
}
/** Return an array of keys that match the `selector` in the target `kv`
* store.
*
* @example Listing keys
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* console.log(await kv.keys({ prefix: ["hello"] }));
* await kv.close();
* ```
*/
keys(
selector: Deno.KvListSelector,
options?: Deno.KvListOptions,
): Promise<Deno.KvKey[]> {
return keys(this.#kv, selector, options);
}
/**
* Set the value for the given key in the database. If a value already
* exists for the key, it will be overwritten.
*
* Optionally an `expireIn` option can be specified to set a time-to-live
* (TTL) for the key. The TTL is specified in milliseconds, and the key will
* be deleted from the database at earliest after the specified number of
* milliseconds have elapsed. Once the specified duration has passed, the
* key may still be visible for some additional time. If the `expireIn`
* option is not specified, the key will not expire.
*
* @example Setting a value
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
* const kv = await openKvToolbox();
* await kv.set(["foo"], "bar");
* ```
*/
set(
key: Deno.KvKey,
value: unknown,
options?: { expireIn?: number },
): Promise<Deno.KvCommitResult> {
return this.#kv.set(key, value, options);
}
/**
* Set the blob value in with the provided key. The blob can be any array
* buffer like structure, a byte {@linkcode ReadableStream}, or a
* {@linkcode Blob}.
*
* The function chunks up the blob into parts which deno be stored in Deno KV
* and should be retrieved back out using the {@linkcode get} function.
*
* Optionally an `expireIn` option can be specified to set a time-to-live
* (TTL) for the key. The TTL is specified in milliseconds, and the key will
* be deleted from the database at earliest after the specified number of
* milliseconds have elapsed. Once the specified duration has passed, the
* key may still be visible for some additional time. If the `expireIn`
* option is not specified, the key will not expire.
*
* @example Setting a `Uint8Array`
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const blob = new TextEncoder().encode("hello deno!");
* await kv.setBlob(["hello"], blob);
* await kv.close();
* ```
*
* @example Setting a `Blob`
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* const blob = new Blob(
* [new TextEncoder().encode("hello deno!")],
* { type: "text/plain" },
* );
* await kv.setBlob(["hello"], blob);
* await kv.close();
* ```
*/
setBlob(
key: Deno.KvKey,
blob:
| ArrayBufferLike
| ArrayBufferView
| ReadableStream<Uint8Array>
| Blob
| File,
options?: { expireIn?: number },
): Promise<Deno.KvCommitResult> {
return set(this.#kv, key, blob, options);
}
/**
* Query a Deno KV store for keys and resolve with any matching keys
* organized into a tree structure.
*
* The root of the tree will be either the root of Deno KV store or if a prefix
* is supplied, keys that match the prefix. Each child node indicates if it
* also has a value and any children of that node.
*
* @example Retrieving a tree
*
* If you had the following keys stored in a datastore:
*
* ```ts
* ["a", "b"]
* ["a", "b", "c"]
* ["a", "d", "e"]
* ["a", "d", "f"]
* ```
*
* And you would get the following results when using `tree()`:
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* console.log(await kv.tree(["a"]));
* // {
* // prefix: ["a"],
* // children: [
* // {
* // part: "b",
* // hasValue: true,
* // children: [{ part: "c", hasValue: true }]
* // }, {
* // part: "d",
* // children: [
* // { part: "e", hasValue: true },
* // { part: "f", hasValue: true }
* // ]
* // }
* // ]
* // }
* await kv.close();
* ```
*/
tree(prefix?: Deno.KvKey, options?: Deno.KvListOptions): Promise<KeyTree> {
return tree(this.#kv, prefix, options);
}
/**
* Resolves with an array of unique sub keys/prefixes for the provided prefix.
*
* This is useful when storing keys and values in a hierarchical/tree view,
* where you are retrieving a list and you want to know all the unique
* _descendants_ of a key in order to be able to enumerate them.
*
* @example Retrieving unique keys
*
* The following keys stored in a datastore:
*
* ```ts
* ["a", "b"]
* ["a", "b", "c"]
* ["a", "d", "e"]
* ["a", "d", "f"]
* ```
*
* The following results when using `unique()`:
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
* console.log(await kv.unique(["a"]));
* // ["a", "b"]
* // ["a", "d"]
* await kv.close();
* ```
*
* If you omit a `prefix`, all unique root keys are resolved.
*/
unique(
prefix?: Deno.KvKey | undefined,
options?: Deno.KvListOptions | undefined,
): Promise<Deno.KvKey[]> {
return unique(this.#kv, prefix, options);
}
/**
* Watch for changes to the given keys in the database. The returned stream
* is a {@linkcode ReadableStream} that emits a new value whenever any of
* the watched keys change their versionstamp. The emitted value is an array
* of {@linkcode Deno.KvEntryMaybe} objects, with the same length and order
* as the `keys` array. If no value exists for a given key, the returned
* entry will have a `null` value and versionstamp.
*
* The returned stream does not return every single intermediate state of
* the watched keys, but rather only keeps you up to date with the latest
* state of the keys. This means that if a key is modified multiple times
* quickly, you may not receive a notification for every single change, but
* rather only the latest state of the key.
*
* The `options` argument can be used to specify additional options for the
* watch operation. The `raw` option can be used to specify whether a new
* value should be emitted whenever a mutation occurs on any of the watched
* keys (even if the value of the key does not change, such as deleting a
* deleted key), or only when entries have observably changed in some way.
* When `raw: true` is used, it is possible for the stream to occasionally
* emit values even if no mutations have occurred on any of the watched
* keys. The default value for this option is `false`.
*
* @example Watching for changes
*
* ```ts
* import { openKvToolbox } from "jsr:@kitsonk/kv-toolbox";
*
* const kv = await openKvToolbox();
*
* const stream = kv.watch([["foo"], ["bar"]]);
* for await (const entries of stream) {
* entries[0].key; // ["foo"]
* entries[0].value; // "bar"
* entries[0].versionstamp; // "00000000000000010000"
* entries[1].key; // ["bar"]
* entries[1].value; // null
* entries[1].versionstamp; // null