1 回答
TA贡献2041条经验 获得超4个赞
这是一个常见的误解,以某种方式“加载”文件。$ref
看看 ajv.js.org 是怎么说的:
$ref使用架构$id作为基本 URI 作为 URI 引用进行解析(请参阅示例)。
和:
您不必在用作架构$id的 URI 上托管架构文件。这些 URI 仅用于标识架构,根据 JSON 架构规范,验证程序不应期望能够从这些 URI 下载架构。
Ajv 不会尝试从以下位置加载此架构:例如:stack://over.flow/string
{
"$id": "stack://over.flow/string",
"type": "string"
}
如果要在另一个架构中引用该架构,它们都需要具有相同的基本URI,例如,stack://over.flow/
{
"$id": "stack://over.flow/object",
"type": "object",
"properties": {
"a": { "$ref": "string#" }
}
}
这里说“在 stack://over.flow/string 导入架构”,所以你最终得到:{ "$ref": "string#" }
{
"$id": "stack://over.flow/object",
"type": "object",
"properties": {
"a": {
"$id": "stack://over.flow/string",
"type": "string"
}
}
}
这允许您组合小架构:
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>
(请注意,在您的示例中,两个架构都不正确。两者都缺少 {“type”: “对象”}。
要回答您的问题:
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>
添加回答
举报