繁体   English   中英

通过相对文件路径解析 $ref

[英]Resolve $ref by relative file path

我想将 json-schemas 拆分为多个本地文件,并尽可能简单直接地引用它们。 为此,我的第一个直觉是$ref指向相对于当前文件的路径。

但是,json-schema 方式似乎没有标准情况,因为$ref是相对于$id解析的,并且“当前文件的路径”不可用。 $id可悲地混合了两个目的(为什么要这样做?):

  • 唯一标识符
  • $ref的基本 URI

我想到了这种解决方法,通过将本地路径注入$id来拖动本地路径,但这显然破坏了$id的另一个目的:

import Ajv from 'ajv';
import * as fs from 'fs/promises';

const load = async (uri: string) => {
  const schema = JSON.parse(await fs.readFile(uri, 'utf8'));
  schema.$id = uri; // do the deed
  return schema;
};

const ajv = new Ajv({ loadSchema: load });

(async () => {
  const startSchema = await load('some/path/example.json');
  const validate = await ajv.compileAsync(startSchema);
})();

幸运的是,就我而言,我真的不在乎$id ,但是没有标准的方法吗? 我无法想象这是一个异常的用例。


示例结构,因为它被请求:

本地文件夹结构示例:

📁 schemas
├─ 📁 sub
│  └─ start.schema.json
└─ referenced.schema.json
  • 开始.schema.json:

     { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://example.com/schemas/id1", "type": "object", "properties": { "bad": { "$ref": "../referenced.schema.json" } } }
  • 引用的.schema.json

     { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://example.com/schemas/id2", "type": "integer" }

已解决将相对于$id ,如果我不替换它: https://example.com/referenced.schema.json ,这是完全错误的。

选项 1:对所有$id使用file://

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "file:///path/to/schemas/id1",
  "type": "object",
  "properties": {
    "bad": { "$ref": "../referenced.schema.json" }
  }
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "file:///path/to/schemas/id2",
  "type": "integer"
}

选项 2:预加载所有模式

import Ajv from 'ajv';
import * as fs from 'fs/promises';

const load = async (uri: string) => {
  return JSON.parse(await fs.readFile(uri, 'utf8'));
};

const ajv = new Ajv();

(async () => {
  ajv.addSchema(await load('schemas/sub/start.schema.json'));
  ajv.addSchema(await load('schemas/referenced.schema.json'));
  const validate = ajv.getSchema("https://example.com/schemas/id1");
})();

暂无
暂无

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

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