node.js 大摇大摆的可空字段

nullable fields in swagger on node.js

我花了很多时间试图找到在 Node.JS 中创建 swagger 文档的解决方案。主库是 swagger-node,您可以在其中创建一个 swagger yaml 文件,然后将您的控制器添加到其中。它会自动在您的应用程序中提供 swagger ui 文档,并根据您在 yaml 中指定的模型对请求和响应进行验证。

这很好,但是我有一个要求ui提醒我想明确地能够return或接受null作为值的一些字段,例如:

{ 
  id: 123,
  description: "string",
  date_sent: null
}

我不想删除 date_sent 键,我想将其明确声明为 null。

swagger 规范不支持 anyOf 我相信 JSON 架构通常是这样做的。

我想知道是否有解决方法?也许某些可用于具有 x-nullable 供应商特定标志的节点的库可以添加,或者以某种方式指定我的 not-required 字段都应该可以为空。

我是否必须自己编写一些东西来获取我的 swagger 文件,然后在验证器中间件运行之前对其进行修改,或者有人可以建议一些解决方法?

SwaggerUI 不支持可空类型(请参阅 here)。但我将可为空的属性用作:

type: ['string','null']

此后 属性 从 UI 中消失,但验证仍然有效。

nullable 字段在 OpenAPI (fka Swagger) 规范 v3.0.0 中受支持,但在 v2.0 中不受支持。可空类型定义如下:

# Can be string or null
type: string
nullable: true

您可以使用默认值 属性,而不是在类型 属性 中添加 null。

Swagger.json 属性 定义示例:

"due_date": {
  "type": "string",
  "description": "Due date",
  "default": "null"
},

这是一个有效的 Swagger 类型定义,并且在 Swagger 中仍然按预期出现 UI。

作为提示,因为我无意中发现了这一点:当我添加

type: string
nullable: true`

如答案 中所述,我的服务仅返回 "fieldName": { "present": true } 而不是实际值!

如果您看到这个,只需将 JsonNullableModule 添加到您的 Jackson 序列化程序中,例如,如果使用 Spring:

@Component
public class JacksonConfiguration {

    @Autowired
    public void configureJackson(ObjectMapper mapper) {
        mapper.registerModule(new JsonNullableModule());
    }

}

然后一切又恢复正常了。