swagger - 为什么带有 Swagger 的 NestJS 会按要求报告我所有的 DTO 属性?

标签 swagger nestjs

我定义了这个 DTO 类。

import { ApiProperty } from "@nestjs/swagger"

export class FormDTO {
    @ApiProperty()
    id: string

    @ApiProperty()
    type: string

    @ApiProperty()
    fieldValues?: Record<string, unknown>

    @ApiProperty()
    parentFormId?: string
}

我预计生成的 OpenAPI 规范会指示 fieldValuesparentFormId 是可选的,但它们是必需的。

enter image description here

根据文档中的示例 here他们应该是可选的。我错过了什么?

使用该 DTO 的唯一方法如下所示,但我认为这无关紧要:

@Post(":id")
createForm(@Body() createFormDto: FormDTO) {
    if (this.formService.hasForm(createFormDto.id)) {
        throw new ConflictException(
            undefined,
            `A form with the id ${createFormDto.id} already exists.`
        )
    }
    return this.formService.createOrUpdateForm(createFormDto)
}

如果重要,这里是 DocumentBuilder

的代码
const config = new DocumentBuilder()
    .setTitle("API")
    .setDescription(
        "description."
    )
    .setVersion("1.0")
    .addBearerAuth(
        {
            type: "http",
            scheme: "bearer",
            bearerFormat: "JWT",
            description: "Paste a valid access token here."
        },
        JWTGuard.name
    )
    .build()

最佳答案

因为这就是 @ApiProperty() 所做的

相反,使用 @ApiPropertyOptional()对于可选字段。

关于swagger - 为什么带有 Swagger 的 NestJS 会按要求报告我所有的 DTO 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71347810/

相关文章:

node.js - 在NestJs中使用Socket IO加入并发布到房间

typescript - NestJS - 避免返回用户密码

java - 阐明 Swagger - 使用泛型时无法生成文档资源模型

azure-devops - Azure DevOps REST API swagger url

node.js - 如何将 swagger 与我的 express 应用程序集成

node.js - 使用 @AuthGuard、Passport 在 NestJS 中进行社交登录

nestjs - 将信息从 NestJS 中间件传递到 Controller /服务

typescript - takeUntil 带过滤器

java - 如何解决 com.fasterxml.jackson.databind.exc.MismatchedInputException?

swagger - 使用未命名对象数组创建 Swagger/开放 API 响应