将$ref中的URI与ajv-cli一起使用



我想根据JSON模式验证JSON文件,该模式使用$ref通过URI:引用外部模式

{
"$schema": "http://json-schema.org/schema#",
"$id": "https://reconciliation-api.github.io/specs/latest/schemas/manifest.json",
"type": "object",
"properties": {
"authentication": {
"$ref": "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/schemas/v2.0/schema.json#/definitions/basicAuthenticationSecurity"
}
}
}

我希望验证器能够动态获取链接的模式,并使用它来验证我的JSON。我已经尝试过使用ajv-cli

ajv test -s my_schema.json -r "\*" -d my_file.json

我希望-r "\*"允许引用任何模式,但我得到了以下错误:

error: can't resolve reference https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/schemas/v2.0/schema.json#/definitions/basicAuthenticationSecurity
from id https://reconciliation-api.github.io/specs/latest/schemas/manifest.json#

ajv-cli是否支持动态获取远程模式?如果没有,是否有其他验证器支持这一点?

https://ajv.js.org/#ref建议您需要启用异步引用解析:https://ajv.js.org/#asynchronous-模式编译

您需要在ajv实例化中定义一个loadSchema函数作为选项,然后调用compileAsync

文档中的示例如下:

var ajv = new Ajv({ loadSchema: loadSchema });
ajv.compileAsync(schema).then(function (validate) {
var valid = validate(data);
// ...
});
function loadSchema(uri) {
return request.json(uri).then(function (res) {
if (res.statusCode >= 400)
throw new Error('Loading error: ' + res.statusCode);
return res.body;
});
}

最新更新