1 回答

TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是一個(gè)常見(jiàn)的誤解,以某種方式“加載”文件。$ref
看看 ajv.js.org 是怎么說(shuō)的:
$ref使用架構(gòu)$id作為基本 URI 作為 URI 引用進(jìn)行解析(請(qǐng)參閱示例)。
和:
您不必在用作架構(gòu)$id的 URI 上托管架構(gòu)文件。這些 URI 僅用于標(biāo)識(shí)架構(gòu),根據(jù) JSON 架構(gòu)規(guī)范,驗(yàn)證程序不應(yīng)期望能夠從這些 URI 下載架構(gòu)。
Ajv 不會(huì)嘗試從以下位置加載此架構(gòu):例如:stack://over.flow/string
{
"$id": "stack://over.flow/string",
"type": "string"
}
如果要在另一個(gè)架構(gòu)中引用該架構(gòu),它們都需要具有相同的基本URI,例如,stack://over.flow/
{
"$id": "stack://over.flow/object",
"type": "object",
"properties": {
"a": { "$ref": "string#" }
}
}
這里說(shuō)“在 stack://over.flow/string 導(dǎo)入架構(gòu)”,所以你最終得到:{ "$ref": "string#" }
{
"$id": "stack://over.flow/object",
"type": "object",
"properties": {
"a": {
"$id": "stack://over.flow/string",
"type": "string"
}
}
}
這允許您組合小架構(gòu):
const ajv = new Ajv;
ajv.addSchema({
"$id": "stack://over.flow/string",
"type": "string"
});
ajv.addSchema({
"$id": "stack://over.flow/number",
"type": "number"
});
const is_string = ajv.getSchema("stack://over.flow/string");
const is_number = ajv.getSchema("stack://over.flow/number");
console.log(is_string('aaa'), is_string(42));
console.log(is_number('aaa'), is_number(42));
const is_ab = ajv.compile({
"$id": "stack://over.flow/object",
"type": "object",
"properties": {
"a": { "$ref": "string#" },
"b": { "$ref": "number#" }
}
});
console.log(is_ab({a: "aaa", b: 42}));
console.log(is_ab({a: 42, b: "aaa"}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.12.2/ajv.min.js"></script>
(請(qǐng)注意,在您的示例中,兩個(gè)架構(gòu)都不正確。兩者都缺少 {“type”: “對(duì)象”}。
要回答您的問(wèn)題:
const ajv = new Ajv;
ajv.addSchema({
"$id": "stack://over.flow/parent.schema",
"type": "object",
"properties": {
"foo": { "type": "string" },
"bar": { "$ref": "child.schema#" }
}
});
ajv.addSchema({
"$id": "stack://over.flow/child.schema",
"type": "object",
"properties": {
"sub1": { "type": "string" },
}
});
const is_parent = ajv.getSchema("stack://over.flow/parent.schema");
const is_child = ajv.getSchema("stack://over.flow/child.schema");
console.log(is_parent({
"foo": "whatever",
"bar": {
"sub1": "sometext"
}
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.12.2/ajv.min.js"></script>
添加回答
舉報(bào)