import type { IDBPDatabase, IDBPObjectStore } from 'idb'; import { hash } from 'ohash'; import type { Value } from '../interfaces/common.js'; import type { AztecAsyncSingleton } from '../interfaces/singleton.js'; import type { AztecIDBSchema } from './store.js'; /** * Stores a single value in IndexedDB. */ export class IndexedDBAztecSingleton implements AztecAsyncSingleton { #_db?: IDBPObjectStore; #rootDB: IDBPDatabase; #container: string; #slot: string; constructor(rootDB: IDBPDatabase, name: string) { this.#rootDB = rootDB; this.#container = `singleton:${name}`; this.#slot = `singleton:${name}:value`; } set db(db: IDBPObjectStore | undefined) { this.#_db = db; } get db(): IDBPObjectStore { return this.#_db ? this.#_db : this.#rootDB.transaction('data', 'readwrite').store; } async getAsync(): Promise { const data = await this.db.get(this.#slot); return data?.value as T; } async set(val: T): Promise { const result = await this.db.put({ container: this.#container, slot: this.#slot, key: [this.#slot], keyCount: 1, value: val, hash: hash(val), }); return result !== undefined; } async delete(): Promise { await this.db.delete(this.#slot); return true; } }