@valbo/json-schema-validation
v1.0.0
Published
Validate JSON schemas with Typescript support
Downloads
1
Readme
@valbo/json-schema-validation
Validate JSON schemas with Typescript support.
Install
npm install @valbo/json-schema-validation
Usage
This package creates a function that validates data against JSON Schemas using Ajv.
To create the function you need an Ajv instance configured with any formats and keywords you need. See ajv-formats and ajv-keywords.
The Ajv instance should also be loaded with any schemas you are going to use to validate data. Schemas should be defined as const objects. See json-schema-to-ts.
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import addStrictFormats from '@valbo/ajv-strict-formats';
import { createValidate } from '@valbo/json-schema-validation';
const personSchema = {
$id: 'person',
type: 'object',
properties: { name: { type: 'string' } },
required: ['name'],
additionalProperties: false,
} as const;
const ajv = new Ajv();
addFormats(ajv);
addStrictFormats(ajv);
ajv.addSchema(personSchema);
const validate = createValidate(ajv);
Use the created function to validate data. If the validation succeeds the returned value is the same data with its type inferred from the provided schema. If the validation fails the function throws a 400 BadRequestError.
const bob = { name: 'bob' };
const typedBob = validate(personSchema, bob);
console.log(typedBob.name); // typedBob type is { name: string }.