Validating against JSON Schema with Ajv

So, let's start by adding Ajv to our project's dependencies:

$ yarn add ajv

Then, in src/validators/users/create.js, import the ajv library as well as our two JSON Schemas:

import Ajv from 'ajv';import profileSchema from '../../schema/users/profile.json';import createUserSchema from '../../schema/users/create.json';import ValidationError from '../errors/validation-error';...
We need to import both schemas because our Create User schema is referencing the Profile schema, and Ajv requires both schemas in order to resolve this reference.

Then, gut out the entire validate function, and replace it with the following:

function validate(req) {  const ajvValidate = new Ajv() .addFormat('email', /^[\w.+]+@\w+\.\w+$/) ...

Get Building Enterprise JavaScript Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.