为什么带有 Swagger 的 NestJS 会按要求报告我的所有 DTO 属性?
我定义了这个 DTO 类。
import { ApiProperty } from "@nestjs/swagger"
export class FormDTO {
@ApiProperty()
id: string
@ApiProperty()
type: string
@ApiProperty()
fieldValues?: Record<string, unknown>
@ApiProperty()
parentFormId?: string
}
我预计生成的 OpenAPI 规范将表明 fieldValues
和 parentFormId
是可选的,但它们是必需的。
根据文档中的示例这里它们应该是可选的。我缺少什么?
使用该 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()
I have this DTO class defined.
import { ApiProperty } from "@nestjs/swagger"
export class FormDTO {
@ApiProperty()
id: string
@ApiProperty()
type: string
@ApiProperty()
fieldValues?: Record<string, unknown>
@ApiProperty()
parentFormId?: string
}
I expected that the generated OpenAPI spec would indicate that fieldValues
and parentFormId
would be optional, but they are required.
According to the example in the docs here they should be optional. What am I missing?
The only method using that DTO looks like this, but I didn't think it would matter:
@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)
}
If it matters, here is the code for the 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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为这就是
@ApiProperty()
所做的,请使用 < code>@ApiPropertyOptional() 用于可选字段。
because that's what
@ApiProperty()
doesInstead, use
@ApiPropertyOptional()
for optional fields.