@valbo/json-schema-validation

Validate JSON schemas with Typescript support.

Usage no npm install needed!

<script type="module">
  import valboJsonSchemaValidation from 'https://cdn.skypack.dev/@valbo/json-schema-validation';
</script>

README

@valbo/json-schema-validation

Validate JSON schemas with Typescript support.

npm (scoped) semantic-release Build Status Coverage Status Known Vulnerabilities

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 }.