/ packages / store / mod.ts
mod.ts
 1  import { codec, type Hash, hash, isHash } from "@massmarket/utils";
 2  import type { AbstractStore } from "./abstract.ts";
 3  
 4  export * from "./mem.ts";
 5  // export * from "./jollytoad.ts";
 6  export * from "./level.ts";
 7  export * from "./abstract.ts";
 8  
 9  /*
10   * ObjectStore stores objects store's objects, as long as they can be encoded as CBOR
11   * It is a key-value store Where
12   * - Keys can be any value that can be encoded as CBOR
13   * - Values can be any value that can be encoded as CBOR
14   */
15  export class ObjectStore {
16    store: AbstractStore;
17    constructor(store: AbstractStore) {
18      this.store = store;
19    }
20  
21    async get(
22      key: codec.CodecValue,
23    ): Promise<codec.CodecValue | undefined> {
24      if (!(key instanceof Uint8Array)) {
25        key = codec.encode(key);
26      }
27      const val = await this.store.get(key as Uint8Array);
28      return val ? codec.decode(val) : undefined;
29    }
30  
31    async set(key: codec.CodecValue, value: codec.CodecValue): Promise<void> {
32      if (!(key instanceof Uint8Array)) {
33        key = codec.encode(key);
34      }
35      const ev = codec.encode(value);
36      await this.store.set(key as Uint8Array, ev);
37    }
38  
39    append(key: codec.CodecValue, value: codec.CodecValue): Promise<void> {
40      if (!(key instanceof Uint8Array)) {
41        key = codec.encode(key);
42      }
43  
44      const ev = codec.encode(value);
45      return this.store.append(key as Uint8Array, ev);
46    }
47  }
48  
49  /**
50   * ContentAddressableStore is a content-addressable store.
51   * Values are stored as CBOR-encoded data.
52   */
53  export class ContentAddressableStore {
54    objStore: ObjectStore;
55    constructor(store: AbstractStore) {
56      this.objStore = new ObjectStore(store);
57    }
58  
59    get(key: Hash): Promise<codec.CodecValue | undefined> {
60      return this.objStore.get(key);
61    }
62  
63    async set(value: codec.CodecValue): Promise<Hash> {
64      if (isHash(value)) {
65        return value;
66      } else {
67        const ev = codec.encode(value);
68        const keyb = await hash(ev);
69        const key = new Uint8Array(keyb);
70        await this.objStore.store.set(key, ev);
71        return key;
72      }
73    }
74  }