UNPKG

@constl/bohr-db

Version:

Type-safe databases for orbit-db.

51 lines 1.67 kB
import Ajv from "ajv"; const ajv = new Ajv({ allowUnionTypes: true }); export const generateListValidator = (schema) => { const validate = ajv.compile(schema); return { validate, }; }; export const generateDictValidator = (schema) => { const validateRoot = ajv.compile(schema); const compileKeySchema = (s) => { // Apparently necessary to avoid AJV error if `nullable: true` and value is `undefined` if (s === true) { return () => true; } return ajv.compile(s); }; const validators = Object.fromEntries(Object.entries(schema.properties || {}).map(([c, p]) => [c, compileKeySchema(p)])); const validateAdditionalProperties = schema.additionalProperties ? compileKeySchema(schema.additionalProperties) : () => false; const validateKey = (v, key) => { const vld = getKeyValidator(key); return vld(v); }; const getKeyValidator = (key) => { return validators[key] || validateAdditionalProperties; }; const supportedKey = (key) => { return !!validators[key] || !!schema.additionalProperties; }; return { validateRoot, validateKey, getKeyValidator, supportedKey, }; }; export const removeUndefinedProperties = (objet) => { return Object.fromEntries(Object.entries(objet) .filter(([_clef, val]) => val !== undefined) .map(([clef, val]) => { return [ clef, typeof val === "object" && !Array.isArray(val) ? removeUndefinedProperties(val) : val, ]; })); }; //# sourceMappingURL=utils.js.map