UNPKG

@constl/bohr-db

Version:

Type-safe databases for orbit-db.

64 lines 2.63 kB
import { splitKey, toNested, } from "@orbitdb/nested-db"; import { removeUndefinedProperties } from "./utils.js"; export const typedNested = ({ db, schema, }) => { const supportedKey = (key) => { const keyComponents = typeof key === "string" ? splitKey(key) : key; let schemaBranch = schema; for (const k of keyComponents) { if (schemaBranch.additionalProperties) return true; if (schemaBranch.properties[k] === undefined) return false; schemaBranch = schemaBranch.properties[k]; } return true; }; // const compiledValidators: {[key in ExtractKeys<T>]: (x: unknown)=>x is GetValueFromKey<T, key>} = {}; /*const validateKeyValue = <K extends ExtractKeys<T>>( val: unknown, key: K ): val is GetValueFromKey<T, K> => { return compiledValidators[key](val) }*/ return new Proxy(db, { get(target, prop) { if (prop === "allAsJSON") { // Todo: type check const typedAllAsJSON = async () => toNested(await db.all()); return typedAllAsJSON; } else if (prop === "setNested" || prop === "putNested") { const typedSetNested = async (keyOrValue, value) => { if (typeof keyOrValue === "string") { // @ts-expect-error types in progress const data = removeUndefinedProperties(value); // Todo: type check return await db.putNested(keyOrValue, data); } else { // @ts-expect-error types in progress const data = removeUndefinedProperties(keyOrValue); // Todo: type check return await db.putNested(data); } }; return typedSetNested; } /*if (prop === "get") { return async <K extends ExtractKeys<T>>(key: K): Promise<GetValueFromKey<T, K> | undefined> => { if (!supportedKey(key)) throw new Error(`Unsupported key ${key}.`); const val = await target.get(key); if (val === undefined) return val; if (validateKeyValue(val, key)) { return val } else { return undefined; }; }; } else { };*/ return target[prop]; }, }); }; //# sourceMappingURL=nested.js.map