node.js 如何管理多个 JSON 模式文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8179137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to manage multiple JSON schema files?
提问by Ray Yun
I'm trying to validate my JSON API using node.js + json-schema.js from commonjs-utils. Just single validation was easy but could not find right way how to manage multiple schema files to enable referencing each other.
我正在尝试使用来自 commonjs-utils 的 node.js + json-schema.js 来验证我的 JSON API。单次验证很容易,但找不到正确的方法来管理多个架构文件以实现相互引用。
Suppose that I got two Models & two APIs.
假设我有两个模型和两个 API。
// book
{
"type": "object",
"properties": {
"title": { "type": "string" },
"author": { "type": "string" }
}
}
// author
{
"type": "object",
"properties": {
"first_name": { "type": "string" },
"last_name": { "type": "string" }
}
}
// authors API
{
"type": "array",
"items": { "$ref": "author" }
}
// books API: list of books written by same author
{
"type": "object",
"properties": {
"author": { "$ref": "author" }
"books": { "type": "array", "items": { "$ref": "book" } }
}
}
Each schema should be divided in separate file and be online? Or Can I combine into single schema file like below? If it is possible, how can I reference local schema?
每个模式应该分成单独的文件并在线?或者我可以像下面这样组合成单个模式文件吗?如果可能,我如何引用本地架构?
// single schema file {
"book": { ... },
"author": { ... },
"authors": { ... },
"books": { ... } }
回答by Flavien Volken
In JSON Schemas, you can either put a schema per file and then access them using their URL (where you stored them), or a big schema with idtags.
在 JSON 模式中,您可以为每个文件放置一个模式,然后使用它们的 URL(存储它们的位置)或带有id标签的大模式访问它们。
Here is for one big file:
这是一个大文件:
{
"id": "#root",
"properties": {
"author": {
"id": "#author",
"properties": {
"first_name": {
"type": "string"
},
"last_name": {
"type": "string"
}
},
"type": "object"
},
// author
"author_api": {
"id": "#author_api",
"items": {
"$ref": "author"
},
"type": "array"
},
// authors API
"book": {
"id": "#book",
"properties": {
"author": {
"type": "string"
},
"title": {
"type": "string"
}
},
"type": "object"
},
// books API: list of books written by same author
"books_api": {
"id": "#books_api",
"properties": {
"author": {
"$ref": "author"
},
"books": {
"items": {
"$ref": "book"
},
"type": "array"
}
},
"type": "object"
}
}
}
You can then reference your validator to one of those sub schemas (which are defined with an id).
然后,您可以将验证器引用到这些子模式之一(用 定义id)。
From outside of your schema, this:
从你的架构之外,这个:
{ "$ref": "url://to/your/schema#root/properties/book" }
is equivalent to this:
相当于:
{ "$ref": "url://to/your/schema#book" }
… which is equivalent, from inside, to this:
...从内部等效于:
{ "$ref": "#root/properties/book" }
or this (still from inside):
或者这个(仍然来自内部):
{ "$ref": "#book" }
See my answer herefor more information.

