如何管理多个JSON模式文件?

Ray*_*Yun 34 schema json jsonschema node.js

我正在尝试使用commonjs-utils中的node.js + json-schema.js来验证我的JSON API.只需单个验证就很容易,但无法找到正确的方法来管理多个模式文件以实现相互引用.

假设我有两个模型和两个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" } }
  }
}  
Run Code Online (Sandbox Code Playgroud)

每个架构应该分成单独的文件并在线?或者我可以组合成单个模式文件,如下所示?如果可能,我如何引用本地模式?

// single schema file {
    "book": { ... },
    "author": { ... },
    "authors": { ... },
    "books": { ... } }
Run Code Online (Sandbox Code Playgroud)

Fla*_*ken 49

在JSON Schemas中,您可以为每个文件放置一个模式,然后使用它们的URL(存储它们的位置)或带有id标记的大模式来访问它们.

这是一个大文件:

{
    "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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将验证器引用到其中一个子模式(使用a定义id).

从您的架构外部,这:

{ "$ref": "url://to/your/schema#root/properties/book" }
Run Code Online (Sandbox Code Playgroud)

相当于:

{ "$ref": "url://to/your/schema#book" }
Run Code Online (Sandbox Code Playgroud)

......从内到外,相当于:

{ "$ref": "#root/properties/book" }
Run Code Online (Sandbox Code Playgroud)

或者这个(仍然来自内部):

{ "$ref": "#book" }
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅我的答案.