1 |
|
2 |
|
3 |
|
4 | import * as Structured from '@worker-tools/structured-json';
|
5 | import { Encoder as BinaryEncoder, Decoder as BinaryDecoder } from 'msgpackr';
|
6 |
|
7 | export interface KVPacker {
|
8 |
|
9 | set(kv: KVNamespace, key: string, value: any, opts?: any): Promise<void>;
|
10 |
|
11 | get(kv: KVNamespace, key: string, opts?: any): Promise<any>;
|
12 | }
|
13 |
|
14 | export class StructuredPacker implements KVPacker {
|
15 |
|
16 | async set(kv: KVNamespace, key: string, value: any, opts?: KVNamespacePutOptions) {
|
17 | await kv.put(key, Structured.stringify(value), opts);
|
18 | }
|
19 |
|
20 | async get(kv: KVNamespace, key: string) {
|
21 | return Structured.fromJSON(await kv.get(key, 'json'));
|
22 | }
|
23 | }
|
24 |
|
25 |
|
26 | export class MsgPacker implements KVPacker {
|
27 |
|
28 | async set(kv: KVNamespace, key: string, value: any, opts?: any): Promise<void> {
|
29 | await kv.put(key, new BinaryEncoder({ structuredClone: true }).encode(value), opts);
|
30 | }
|
31 |
|
32 | async get(kv: KVNamespace, key: string): Promise<any> {
|
33 | const data = await kv.get(key, 'arrayBuffer');
|
34 | return data && new BinaryDecoder({ structuredClone: true }).decode(new Uint8Array(data));
|
35 | }
|
36 | }
|
37 |
|
38 | export { StructuredPacker as TypesonPacker }
|