简体   繁体   English

AJV - 引用外部架构而不先添加它

[英]AJV - Reference external schema without adding it first

Is it possible to use AJV to reference a schema that was previously not added through addSchema() ?是否可以使用 AJV 来引用以前未通过addSchema()添加的架构?

I want to resolve a reference like this:我想解决这样的参考:

{
    "$schema": "http://json-schema.org/draft-07/schema",
    "type": "object",
    "additionalProperties": false,
    "properties": {
        "id": {
            "$ref": "project-id.schema.json#/definitions/id"
        }
    }
}

without explicitly adding project-id.schema.json first.无需先显式添加project-id.schema.json

Given给定的

answer.json回答.json

{
  "$id": "stackoverflow://schemas/answer.json",
  "type": "object",
  "properties": {
    "id": {
      "$ref": "id.json#"
    }
  }
}

id.json id.json

{
  "$id": "stackoverflow://schemas/id.json",
  "type": "string"
}

Adding all schemas at once via the schemas option通过schemas选项一次添加所有模式

const Ajv = require('ajv');
const ajv = new Ajv({
  schemas: [
    require('./id.json'),
    require('./answer.json')
  ]
});

const validate = ajv.getSchema('stackoverflow://schemas/answer.json');

validate(42);
//=> false
validate({id: 42});
//=> false
validate({id: '🌯'});
//=> true

Loading referenced schemas with the loadSchema option使用loadSchema选项加​​载引用的模式

In this case you do need to pass the schema you want to compile as an object but if that schema contains references to other schemas not known by Ajv already, these will be loaded via loadSchema :在这种情况下,您确实需要将要编译的架构作为对象传递,但如果该架构包含对 Ajv 未知的其他架构的引用,则这些将通过loadSchema加载:

const Ajv = require('ajv');
const ajv = new Ajv({
  loadSchema: function (uri) {
    return new Promise((resolve, reject) => {
      if (uri === 'stackoverflow://schemas/id.json') {
        resolve(require('./id.json')); // replace with http request for example
      } else {
        console.log('wat')
        reject(new Error(`could not locate ${uri}`));
      }
    });
  }
});

const test = async () => {
  // Schemas referenced in answer.json will be loaded by the loadSchema function
  const validate = await ajv.compileAsync(require('./answer.json'));
  validate(42) //=> false
  validate({id: 42}) //=> false
  validate({id: '🌯'}) //=> true
}

test();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM