[英]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
。
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"
}
schemas
optionschemas
选项一次添加所有模式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
loadSchema
optionloadSchema
选项加载引用的模式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.