簡體   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