【发布时间】:2020-09-15 16:13:56
【问题描述】:
我有一个描述我的 API 的 JSON 模式文件。它包含一些定义以及我想忽略的 codegen 中的一些残留部分(properties 和 required 字段):
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"CreateBook": {
"properties": {
"title": {"type": "string"},
"author": {"type": "string"},
"numPages": {"type": "number"}
},
"required": ["title", "author"]
},
"CreateShelf": {
"properties": {
"books": {"type": "array", "items": {"type": "string"}}
},
"required": ["books"]
}
},
"properties": {
"/api/create-book": {
"properties": {"type": {"post": {"$ref": "#/definitions/CreateBook"}}},
"required": ["post"],
"type": "object"
},
"/api/create-shelf": {
"properties": {"type": {"post": {"$ref": "#/definitions/CreateShelf"}}},
"required": ["post"],
"type": "object"
}
},
"required": ["/api/create-book", "/api/create-shelf"],
"type": "object"
}
我想根据定义验证请求。我想完全忽略 properties 和 required 字段,它们描述了 API 本身的形状,而不是单个请求。
鉴于我期望的 CreateBook 请求和这个 JSON 模式,我应该如何验证它?
这是我尝试过的:
const ajv = new Ajv();
const validate = ajv.compile(jsonSchema);
const body = {
author: 'Roald Dahl',
numPages: 234,
// missing title
};
if (!validate(body, '#/definitions/CreateBook')) {
console.log(validate.errors);
}
此日志:
[
{
keyword: 'required',
dataPath: '#/definitions/CreateBook',
schemaPath: '#/required',
params: { missingProperty: '/api/create-book' },
message: "should have required property '/api/create-book'"
}
]
所以它忽略了dataPath 参数('#/definitions/CreateBook')。这样做的正确方法是什么?我需要为每种请求类型创建一个新架构吗?
【问题讨论】:
标签: jsonschema ajv