Search code examples
jsonjsonschemaajv

How to use ajv with dependent json-schemas?


I am tryng to make ajv work with two json-schemas, one dependent on the other. Here an example (reduced) of my schemas:

types.json

{
    "$schema":"http://json-schema.org/draft-04/schema#",
    "$id": "http://a.site.org/schemas/types.json",
    "type": "object",
    "definitions": {
        "gender":{"enum": ["male", "female"]}
    },
    "properties":{
        "gender":{"$ref": "#/definitions/gender"}
    }
}

definitions.json

{
"$schema":"http://json-schema.org/draft-04/schema#",
"$id": "http://a.site.org/schemas/definitions.json",
"definitions": {
    "person":{
        "type":"object",
        "properties": {
            "username":{"type":"string"},
            "password": {"type":"string"},
            "name":{"type":"string"},
            "surname":{"type":"string"},
            "sex":{"$ref": "types.json#/properties/gender"},
            "email":{"type":"string", "format":"email"}
        },
        "required":["name", "surname", "sex", "email"]
    }
},
"type":"object",
"properties": {
    "person": {"$ref": "#/definitions/person"}
    }
}

From node, I use ajv like this:

import Ajv, {JSONSchemaType, DefinedError} from "ajv"
import {Gender} from "./types"
import {Person} from "./definitions";
const ajv = new Ajv()

const types : JSONSchemaType<Gender>= require("../types.json");
const PersonSchema : JSONSchemaType<Person> = require('../definitions.json').definitions.person;

const isPerson = ajv.addSchema(types).compile(PersonSchema);
const riccardo:Person={name: "Riccardo", surname: "surname", sex: "male", email: "[email protected]"};
const personValid = isPerson(riccardo);
if (!personValid) console.log(isPerson.errors)

The error I get is:

Error: no schema with key or ref "http://json-schema.org/draft-04/schema#"

UPDATE: If I delete the "$schema ..." from types.json, the error I get is:

MissingRefError: can't resolve reference types.json#/definitions/gender from id #

I used this reference: https://github.com/ajv-validator/ajv/blob/master/docs/validation.md#modular-schemas

Does anyone know what I am doing wrong?


Solution

  • As of version 7, support for draft-04 has been removed. If you want to use draft-04, you need to use version 6 of ajv.