Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define DTO for ApiParam and ApiQuery

Tags:

swagger

nestjs

I'm using the nestjs swagger module and want to create my API documentation. For endpoints relying on the request body I can assign a DTO class to the docs like

@ApiBody({ type: CreateUserDTO })

Some endpoints also rely on the request params or queries. For params I would do something like

@ApiParam({ type: GetUserByIdDTO })

(I know this is a bad example because there is no need for a DTO for a user id but let's assume you want to validate your params with a DTO class using class-validator)

but I'm getting this error

Argument of type '{ type: typeof GetUserByIdDTO; }' is not assignable to parameter of type 'ApiParamOptions'. Property 'name' is missing in type '{ type: typeof GetUserByIdDTO; }' but required in type 'ApiParamMetadata'.

For queries I would do something like

@ApiQuery({ type: GetUsersDTO })

and get this error

Argument of type '{ type: typeof GetUsersDTO; }' is not assignable to parameter of type 'ApiQueryOptions'. Property 'name' is missing in type '{ type: typeof GetUsersDTO; }' but required in type 'ApiQueryMetadata'.

So the APIBody decorator seems to work fine but how can I fix my APIParam and APIQuery decorators?

like image 495
Question3r Avatar asked Apr 26 '20 12:04

Question3r


1 Answers

@ApiQuery and @ApiParam are needed when working with named params / query, like @Query('pageSize') o @Param('id'). In this case NestJS Swagger module should extract information directly from the DTO object specified, like:

async findElements(@Query() query: ElementsQueryDto) {
  // ...
}

An important thing to note is that Dtos should be classes, not interfaces.

like image 106
leonardfactory Avatar answered Oct 22 '22 18:10

leonardfactory