堆
- 快
数据
- 使用 addSchema 方法添加了几个架构:
server.addSchema({
$id: 'event',
type: 'object',
properties: {
event_id: {
$ref: 'id'
},
address: {
$ref: 'address'
},
starttime: {
$ref: 'time'
},
name: {
type: 'string'
}
},
required: ['event_id', 'address', 'starttime']
})
server.addSchema({
$id: 'callEvent',
type: 'object',
allOf: [{ $ref: 'event' }],
properties: {
type: {
type: 'string',
const: 'call'
},
num: {
type: 'integer'
},
result: {
type: 'integer',
minimum: 0,
maximum: 3
}
},
required: ['type', 'num', 'result'],
unevaluatedProperties: false
})
server.addSchema({
$id: 'appEvent',
type: 'object',
allOf: [{ $ref: 'event' }],
properties: {
type: {
type: 'string',
const: 'app'
}
},
required: ['type'],
unevaluatedProperties: false
})
- GET 端点的架构:
{
"response": {
"200": {
"type": "object",
"additionalProperties": {
"type": "array",
"items": {
"type": "object",
"oneOf": [
{ "$ref": "appEvent" },
{ "$ref": "callEvent" }
]
}
}
}
}
}
我的目标:我需要指定响应返回一个对象,其中的键可以是任意值,并且属性是一个数组,其中的元素可以匹配任何指定的模式。
预期有效结果:
{
"otherkey": [
{
"event_id": 1,
"address": "string",
"starttime": " 00:00",
"name": "string",
"type": "app" // this scheme appEvent
},
{
"event_id": 2,
"address": "string",
"starttime": " 06:08",
"name": "string",
"type": "call",
"num": 0,
"result": 3 // this scheme callEvent
}
],
"otherkey2": [
{
"event_id": 1,
"address": "string",
"starttime": " 00:00",
"name": "string",
"type": "app" // this scheme appEvent
}
],
"otherkey3": [
{
"event_id": 2,
"address": "string",
"starttime": " 06:08",
"name": "string",
"type": "call",
"num": 0,
"result": 3 // this scheme callEvent
}
]
}
实际结果:
{
"statusCode": 500,
"error": "Internal Server Error",
"message": "The value of '#/additionalProperties/items' does not match schema definition."
}
如果我做错了什么,请纠正我。但根据架构https://json-schema.org/draft-07/schema,这应该可以正常工作。
注意:我也在我的堆栈中使用@fastify/swagger
和@fastify/swagger-ui
。在生成的 Swagger 文档中,此端点的示例按我的预期显示。
Swagger 中的示例如下:
{
"additionalProp1": [
{
"event_id": 1,
"address": "string",
"starttime": "23:07",
"name": "string",
"type": "string"
},
{
"event_id": 1,
"address": "string",
"starttime": "22:40",
"name": "string",
"type": "string",
"num": 0,
"result": 3
}
],
"additionalProp2": [
{
"event_id": 1,
"address": "string",
"starttime": "23:07",
"name": "string",
"type": "string"
},
{
"event_id": 1,
"address": "string",
"starttime": "22:40",
"name": "string",
"type": "string",
"num": 0,
"result": 3
}
],
"additionalProp3": [
{
"event_id": 1,
"address": "string",
"starttime": "23:07",
"name": "string",
"type": "string"
},
{
"event_id": 1,
"address": "string",
"starttime": "22:40",
"name": "string",
"type": "string",
"num": 0,
"result": 3
}
]
}
我曾尝试搜索有关此主题的不同信息,但所有示例都显示 oneOf 和 anyOf 的用法与我使用的方式相同。
通常,如果模式中存在无效键或模式不正确,Fastify 会在服务器的构建和启动阶段抛出错误,但在这种情况下不会这样做。