Compile multiple json schemas at once with Ajv.js

Viewed 2025

I have been searching for a way to compile multiple json schemas with ajv (Another JSON Schema Validator) at once. I have tried following approach and it works (code sample below) but I'm not sure that it is the proper way to do it, because according to ajv API here https://www.npmjs.com/package/ajv#api

Function compile is defined as .compile(Object schema) -> Function

This definition doesn't mention accepting boolean as parameter, however when I've tried using ajv.compile() without any parameters, I've got this error:

Error: schema should be object or boolean

But after calling ajv.compile(true) the code ran without any errors and I guess passing true as an argument means to compile all schemas defined in options, but as I said, I couldn't find anything about this assumption of mine in avs docs. (I have my schemas defined in schemas.js file)

Is this the proper way to compile multiple schemas?

var express = require('express');
var router = express.Router();

const schemas = require('../schemas.js');

var Ajv = require('ajv');
var ajv = new Ajv({
    allErrors: true,
    schemas: [schemas.profile, schemas.vzor]
});

var validate = ajv.compile(true);

router.post('/schema_test/', function (req, res, next) {

    var valid = ajv.validate('profile', req.body);
    if (valid) 
        console.log('Valid!');
    else
        console.log('Invalid: ' + ajv.errorsText(validate.errors));

    return res.sendStatus(200);
});
1 Answers

Have you seen the documentation? There the snippet below is available:

var schema = {
  "$id": "http://example.com/schemas/schema.json",
  "type": "object",
  "properties": {
    "foo": { "$ref": "defs.json#/definitions/int" },
    "bar": { "$ref": "defs.json#/definitions/str" }
  }
};

var defsSchema = {
  "$id": "http://example.com/schemas/defs.json",
  "definitions": {
    "int": { "type": "integer" },
    "str": { "type": "string" }
  }
};

var ajv = new Ajv;
var validate = ajv.addSchema(defsSchema)
                  .compile(schema);

I believe that when you call ajv.compile(true), true is treated as an additional valid schema that accepts everything except empty messages. So, I think you do not want pass true to compile().

Related