UNPKG

1.47 kBPlain TextView Raw
1// deno-lint-ignore-file no-explicit-any
2// import 'https://cdn.skypack.dev/@cloudflare/workers-types@3.11.0?dts'
3
4import * as Structured from '@worker-tools/structured-json';
5import { Encoder as BinaryEncoder, Decoder as BinaryDecoder } from 'msgpackr';
6
7export interface KVPacker {
8 // @ts-ignore: deno only
9 set(kv: KVNamespace, key: string, value: any, opts?: any): Promise<void>;
10 // @ts-ignore: deno only
11 get(kv: KVNamespace, key: string, opts?: any): Promise<any>;
12}
13
14export class StructuredPacker implements KVPacker {
15 // @ts-ignore: deno only
16 async set(kv: KVNamespace, key: string, value: any, opts?: KVNamespacePutOptions) {
17 await kv.put(key, Structured.stringify(value), opts);
18 }
19 // @ts-ignore: deno only
20 async get(kv: KVNamespace, key: string) {
21 return Structured.fromJSON(await kv.get(key, 'json'));
22 }
23}
24
25/** @deprecated This doesn't match structured clone algorithm close enough. Not recommended */
26export class MsgPacker implements KVPacker {
27 // @ts-ignore: deno only
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 // @ts-ignore: deno only
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
38export { StructuredPacker as TypesonPacker }