问题描述
我花了很多时间试图找到在 Node.JS 中创建 swagger 文档的解决方案.主库是 swagger-node,您可以在其中创建一个 swagger yaml 文件,然后将控制器添加到其中.它会自动在您的应用程序中提供 swagger ui 文档,并对请求进行验证响应您在 yaml 中指定的模型.
I've spent a bunch of time trying to find a solution for creating swagger docs in Node.JS. The main library is swagger-node, in which you create a swagger yaml file and then add your controllers to it. It automatically provides swagger ui docs in your app and does validation on the request & response against the models you specify in your yaml.
这很简洁,但是我有一个要求,我希望某些字段能够显式返回或接受 null
作为值,例如:
This is neat, however I have a requirement that some fields I want to explicitly be able to return or accept null
as a value, for instance:
{
id: 123,
description: "string",
date_sent: null
}
我不想删除 date_sent
键,我想明确地将其声明为 null.
I don't want to delete the date_sent
key, I want to explicitly state it as null.
swagger 规范不支持 anyOf
我相信 JSON 模式通常是这样做的.
The swagger spec does not support anyOf
which is how JSON schema normally does this I believe.
我想知道是否有解决方法?也许某些可用于节点的库具有您可以添加的 x-nullable
供应商特定标志,或者以某种方式指定我的非必填字段都应该可以为空.
I'm wondering if there's a workaround? Perhaps some library available for node that has a x-nullable
vendor specific flag you can add, or some way of specifying that my not-required fields should all be nullable.
我是否必须自己编写一些东西来获取我的 swagger 文件,然后在验证器中间件运行之前对其进行修改,还是有人可以建议一些解决方法?
Am I going to have to write something myself that takes my swagger file and then modifies it before the validator middleware runs, or is there some workaround someone can suggest?
推荐答案
SwaggerUI 不支持可空类型(请参阅 这里).但我使用可为空的属性:
SwaggerUI doesn't support nullable types (please, see here). But I used nullable properties as:
type: ['string','null']
之后此属性从 UI 中消失,但验证仍然有效.
After that this property disappears from UI, but validation still worked.
这篇关于node.js 上招摇的可空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!