-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpacker.ts
38 lines (33 loc) · 1.49 KB
/
packer.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
// deno-lint-ignore-file no-explicit-any
// import 'https://cdn.skypack.dev/@cloudflare/[email protected]?dts'
import * as Structured from 'https://ghuc.cc/worker-tools/structured-json/index.ts';
import { Encoder as BinaryEncoder, Decoder as BinaryDecoder } from 'https://cdn.skypack.dev/[email protected]?dts';
export interface KVPacker {
// @ts-ignore: deno only
set(kv: KVNamespace, key: string, value: any, opts?: any): Promise<void>;
// @ts-ignore: deno only
get(kv: KVNamespace, key: string, opts?: any): Promise<any>;
}
export class StructuredPacker implements KVPacker {
// @ts-ignore: deno only
async set(kv: KVNamespace, key: string, value: any, opts?: KVNamespacePutOptions) {
await kv.put(key, Structured.stringify(value), opts);
}
// @ts-ignore: deno only
async get(kv: KVNamespace, key: string) {
return Structured.fromJSON(await kv.get(key, 'json'));
}
}
/** @deprecated This doesn't match structured clone algorithm close enough. Not recommended */
export class MsgPacker implements KVPacker {
// @ts-ignore: deno only
async set(kv: KVNamespace, key: string, value: any, opts?: any): Promise<void> {
await kv.put(key, new BinaryEncoder({ structuredClone: true }).encode(value), opts);
}
// @ts-ignore: deno only
async get(kv: KVNamespace, key: string): Promise<any> {
const data = await kv.get(key, 'arrayBuffer');
return data && new BinaryDecoder({ structuredClone: true }).decode(new Uint8Array(data));
}
}
export { StructuredPacker as TypesonPacker }