UNPKG

data-to-jsonschema-to-ts

Version:

Convert plain javascript objects to JSON Schema and TypeScript typings

24 lines 836 B
import { Ajv } from "ajv"; const ajv = new Ajv({ allErrors: true }); /** * Compile a JSON Schema into a reusable validator function. * * The returned validator runs the data against the schema and reports * **all** failing constraints (not just the first). Compilation happens * once per call to this function; reuse the returned validator to avoid * recompiling. * * @param schema - JSON Schema to validate against. * @returns A function `(data) => { valid, errors? }`. `errors` is `undefined` on success. */ export function createJsonSchemaValidator(schema) { const validate = ajv.compile(schema); return function validator(data) { const valid = validate(data); return { valid, errors: valid ? undefined : validate.errors, }; }; } //# sourceMappingURL=index.js.map