'How can I have multiple DTO's for NestJS Request Body/Swagger

so I have a route that can accept two different DTO's. I'm having difficulty getting these two DTO's to link/show up on swagger. I'm using the swagger plugin with NestJS. I know in raw swagger you can do something like. Any ideas?

Request:
  oneOf:
    - $ref: "#/components/schemas/RequestOneType"
    - $ref: "#/components/schemas/RequestTwoType"

Any example of what I have right now is like

async initApp(@Body() req: RequestOneDto | RequestTwoDto , @Res({ passthrough: true }) res: Response) {

}

export class RequestOneDto { @Length(1,10); name: string

@Max(10) value: number }

export class RequestTwoDto { @Length(1,15); name: string

@Max(15) value: number

state: 'New York' }



Solution 1:[1]

Have you tried this way?

@ApiExtraModels(RequestOneDto, RequestTwoDto)
@ApiBody({
  schema: {
    oneOf: [
      {
        $ref: getSchemaPath(RequestOneDto),
      },
      {
        $ref: getSchemaPath(RequestTwoDto),
      },
    ],
  },
})
async initApp(@Body() body: RequestOneDto | RequestTwoDto) {}

You can import ApiBody, ApiExtraModels from @nestjs/swagger

If you dont want to include the models explicitly you can register em in one place as

const document = SwaggerModule.createDocument(app, options, {
  extraModels: [RequestOneDto, RequestTwoDto],
});

And here is more info

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 n1md7