【问题标题】:Using URIs in $ref with ajv-cli通过 ajv-cli 在 $ref 中使用 URI
【发布时间】:2020-03-27 10:56:25
【问题描述】:

我想根据 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 是否支持即时获取远程模式?如果没有,是否有任何其他验证器支持该功能?

【问题讨论】:

    标签: json jsonschema ajv


    【解决方案1】:

    https://ajv.js.org/#ref 的文档建议您需要启用异步引用解析:https://ajv.js.org/#asynchronous-schema-compilation

    你需要在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;
      });
    }
    

    【讨论】:

    • 谢谢!所以可以在 ajv 本身中做到这一点 - 但我想知道 CLI 是否支持这一点?
    • 我怀疑它,因为你必须提供一个功能。
    • 请注意,如果您想在前端使用request 模块执行此操作,可以使用fetch,例如:async function loadSchema(uri) { const res = await fetch(uri); if (res.status >= 400) { throw new Error('Loading error: ' + res.status); } return await res.json(); }
    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 2020-09-19
    • 2017-08-10
    • 2011-03-25
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多