Validating JSON Hyper Schema with ajv

750 views Asked by At

I'm trying to use the ajv module to validate some input. I got it working with regular JSON Schema But I wanted to validate multiple routes and use the links data to build docs but I'm confused how to set it up. Here is my schema:

 {
      "$schema": "http://json-schema.org/draft-04/hyper-schema#",
      "title": "Questions",
      "type": "object",
      "definitions": {
        "companyId": {
          "type": "string",
          "minLength": 3,
          "maxLength": 20
        }
      },
      "links":[
        {
          "title": "List",
          "href": "/questions",
          "method": "POST",
          "rel": "self",
          "schema": {
            "properties": {
              "companyId": {
                "$ref": "#/definitions/companyId"
              }
            },
            "required": ["companyId"]
          }
        }
      ]
    }

And my code:

const schema = require('./schemas/questions.json');
const hyperSchema = require('../schemas/hyper-schema.json');
const Ajv = require('ajv');

const ajv = new Ajv({ allErrors: true, v5: true });
ajv.addMetaSchema(hyperSchema, undefined, true);

const validate = ajv.compile(schema);
const valid = validate(input);
console.log(valid)

My question is, once I load my schema how do I tell ajv what to link schema to validate against? I'll have multiple routes (links) with differnt input to validate.

Also, is the schema setup correctly?

1

There are 1 answers

0
jabbermonkey On BEST ANSWER

In case anyone else needs this, I used a JSON pointer like this:

const ajv = new Ajv({ allErrors: true, removeAdditional: true, v5: true });
ajv.addMetaSchema(hyperSchema, undefined, true);
ajv.addSchema(schema, 'questions.json');
const valid = ajv.validate({ $ref: 'questions.json#/links/0/schema' }, input);