How to reference other json schemas on AJV?

Viewed 19

I have the following json object:

{
    "data" : {
        "brand" : {
            "name" : "",
            "type" : ""
        }
    },
    "links" : {
        "first" : "https://someurl/first",
        "next" : "https://someurl/next",
        "previous" : "https://someurl/next",
        "last" : "https://someurl/last",
        "self" : "https://someurl/this"
    }
}

To validate it using AJV I can use the following schema:

const schema = {
    type: "object",
    properties: {
        data: {
            type: "object",
            properties: {
                brand: {
                    type: "object",
                    properties: {
                        name: "string",
                        type: "string"
                    }
                }
            },
            required: ["brand"]
        },
        links: {
            type: "object",
            properties: {
                first : "string",
                next : "string",
                previous : "string",
                last : "string",
                self : "string"
            },
            required: ["first","last","self"]
        },
    },
    required: ["data","links"],
    additionalProperties: false
}

...and I'm validating it using a code like this (considering mydata has a valid or invalid object):

import Ajv from 'ajv';
const ajv = new Ajv();
const valid = ajv.validate(schema, mydata)
if (!valid) { 
    console.log(ajv.errors)
}

Considering that "links" object will be used multiple times on other schemas, I would like a way to move it to a separated file and just reference it on the schema above. I've tried some "solutions" I found on internet, but they look very confuse and didn't work.

Is there a clear/easy way to declare these kind of "shared schemas" and use it on the main schema?

Thanks

0 Answers
Related