Thomas
Thomas

Reputation: 1821

Why does NestJS with Swagger report all my DTO properties as required?

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.

enter image description here

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()

Upvotes: 4

Views: 2411

Answers (1)

Micael Levi
Micael Levi

Reputation: 6665

because that's what @ApiProperty() does

Instead, use @ApiPropertyOptional() for optional fields.

Upvotes: 6

Related Questions