apr*_*ity 5 node.js swagger swagger-2.0 openapi
在使用swagger2(openAPI)构建rest api时,我想允许查询参数station_id支持以下内容:
我使用下面的大方定义(字符串数组)来尝试完成此操作:
parameters:
- name: station_id
in: query
description: filter stations by station_id
required: false
type: array
items:
type: string
Run Code Online (Sandbox Code Playgroud)
使用此定义,除?station_id = 23以外,所有其他示例均适用,因为挥舞性验证失败并显示以下消息:
{
"message": "Validation errors",
"errors": [
{
"code": "INVALID_REQUEST_PARAMETER",
"errors": [
{
"code": "INVALID_TYPE",
"params": [
"array",
"integer"
],
"message": "Expected type array but found type integer",
"path": [],
"description": "filter stations by station_id"
}
],
"in": "query",
"message": "Invalid parameter (station_id): Value failed JSON Schema validation",
"name": "station_id",
"path": [
"paths",
"/stations",
"get",
"parameters",
"0"
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果我像?station_id = '23'一样引用了station_id,则验证通过并得到正确的响应。但我真的希望不必使用引号。像联合类型这样的东西可以帮助解决这个问题,但是据我所知,它们不受支持。
我还有另一个端点/ stations / {id},它可以处理单个id的情况,但是仍然有许多其他(非主键)数字字段,我想以上面指定的方式进行过滤。例如station_latitude。
有什么想法可以解决-也许我可以以某种方式使用模式(regex)?如果在摇摇欲坠的定义中没有解决方法,有没有办法调整或绕过验证器?这是一个使用swagger-node的nodejs项目,我将swagger-express-mw的版本升级到了0.7.0。
小智 2
我认为您需要的是类似于 JSON Schema 提供的anyOfor关键字,以便您可以将参数的类型定义为数字或字符串。OpenAPI 3.0支持,但 2.0 不支持。OpenAPI 3.0 定义如下所示:oneOfstation_idanyOfoneOf
openapi: 3.0.0
...
paths:
/something:
get:
parameters:
- in: query
name: station_id
required: true
explode: false
schema:
oneOf:
- type: integer # Optional? Array is supposed to cover the use case with a single number
example: 23
- type: array
items:
type: integer
minItems: 1
example: [23, 45]
- type: string
oneOf:
- pattern: '^\[\d+:\d+]$'
- pattern: '^\d+%$'
# or using a single pattern
# pattern: '^(\[\d+:\d+])|(\d+%)$'
example: '[3:14]'
Run Code Online (Sandbox Code Playgroud)
作为替代方案,也许您可以添加sortBy、skip和limit参数以保持类型统一。例如:?sortBy=station_id&skip=10&limit=10将仅检索站 10 - 20。
| 归档时间: |
|
| 查看次数: |
1393 次 |
| 最近记录: |