UNPKG

@constl/bohr-db

Version:

Type-safe databases for orbit-db.

56 lines 2.35 kB
import { generateDictValidator, removeUndefinedProperties } from "./utils.js"; export const typedKeyValue = ({ db, schema, }) => { const { validateRoot, validateKey, getKeyValidator, supportedKey } = generateDictValidator(schema); return new Proxy(db, { get(target, prop) { if (prop === "get") { return async (key) => { if (!supportedKey(key)) throw new Error(`Unsupported key ${key}.`); const val = await target.get(key); if (val === undefined) return val; const valid = validateKey(val, key); return valid ? val : undefined; }; } else if (prop === "put" || prop === "set") { return async (key, value) => { if (!supportedKey(key)) throw new Error(`Unsupported key ${key}.`); if (typeof value === "object" && !Array.isArray(value)) { value = removeUndefinedProperties(value); } const valid = validateKey(value, key); if (valid) return await target.put(key, value); else throw new Error(JSON.stringify(getKeyValidator(key).errors, undefined, 2)); }; } else if (prop === "all") { return async () => { const all = await target.all(); return all.filter((x) => validateKey(x.value, x.key)); }; } else if (prop === "allAsJSON") { return async () => { const all = await target.all(); const data = Object.fromEntries(all.map((x) => [x.key, x.value])); const valid = validateRoot(data); if (valid) { return data; } else { throw new Error(JSON.stringify(validateRoot.errors, undefined, 2)); } }; } else { return target[prop]; } }, }); }; //# sourceMappingURL=keyvalue.js.map