Swagger: Using the dto class and @Body decorator does not work as expected.

Created on 22 Mar 2018  路  13Comments  路  Source: nestjs/swagger

The code:

DTOs:

import {
  ApiModelProperty,
} from '@nestjs/swagger';

import { UserDto } from './user.dto';

export class CreateUserDto extends UserDto {

  @ApiModelProperty()
  readonly password: string;

  @ApiModelProperty()
  readonly confirmPassword: string;
}
import {
  ApiModelProperty,
  ApiModelPropertyOptional,
} from '@nestjs/swagger';


export class UserDto {

  @ApiModelPropertyOptional()
  readonly firstName?: string;

  @ApiModelPropertyOptional()
  readonly lastName?: string;

  @ApiModelProperty()
  readonly email: string;
}

Controller:

@ApiUseTags('users')
@Controller('users')
export class UsersController {

  constructor(private readonly usersService: UsersService) {}

  /**
   * Creates a new User (register)
   *
   * @param createUserDto
   * @return Promise<void>
   */
  @Post()
  @ApiOperation({ title: 'Create a new User' })
  @ApiResponse({
    status: HttpStatus.CREATED,
    description: 'The record has been successfully created.',
  })
  @ApiResponse({
    status: HttpStatus.BAD_REQUEST,
    description: 'confirm password doesn\'t match the password, or the payload is invalid',
  })
  @ApiResponse({
    status: HttpStatus.CONFLICT,
    description: 'Email already in use',
  })
  @ApiResponse({ status: HttpStatus.FORBIDDEN, description: 'Forbidden.' })
  @ApiResponse({ status: HttpStatus.UNAUTHORIZED, description: 'Unauthorized.' })
  async createUser(@Body() createUserDto: CreateUserDto) {
    await this.usersService
      .create(createUserDto)
      .catch(this._handleError);
  }

  / * <...> */

}

The result:

screenshot 2018-03-22 03 05 24


However, using the following is fixing the Swagger UI:

  @ApiImplicitBody({
    name: 'role data',
    type: CreateUserDto,
  })
potential issue

Most helpful comment

The same is for the @Query decorator

All 13 comments

The same is for the @Query decorator

I also encountered the same problem

I'm trying to reproduce this issue. What about this sample: https://github.com/nestjs/nest/tree/master/sample/11-swagger? Do you face a similar problem? What Nest version do you use?

I did not have such a problem before changing dependencies in package.json. It sounds weird, but when I tried to revert to previous dependencies, problem was still here. Surprisingly, I was trying to solve issue with pipes, because built-in pipes did not work for NestJs 5.0-rc.2.

Dependencies that I changed were: rxjs 5.5.6 -> 6.0.0. Some kinda strange

This issue is not solved for Nest v5.0.0 yet.

Small update from my team.

It has started working.

I suspect that it has something to do with issues in DTO declarations (our mistakes), like using an Interface as a property type in DTO. If I'm not 100% sure, but I think it has started working after we eliminated such declarations by replacing interfaces with other DTO classes.

We did upgrade some dependencies but I don't think it was the reason.


But now we have another issue: @ApiBearerAuth doesn't do a thing! It worked previously but suddenly it stopped.

Will try to find when it happened and why. So far, I have no idea.

I believe I'm seeing the same issue for a project that I just returned to.

+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]

I have this controller

@Controller('user')
@ApiUseTags('users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post()
  @UsePipes(new PipesModelParser())
  @ApiOperation({ title: 'register new user' })
  async create(@Body() user: User): Promise<User> {
    const newUser = await this.userService.create(user);
    this.userService.createToken(user);
    return newUser;
  }
  ...

And the swagger UI shows no body parameter.

In the swagger console I get

root-injects.js:95 TypeError: Cannot read property 'anyOf' of undefined
    at e (fn.js:77)
    at e (fn.js:60)
    at configure-map.js:43
    at t.getSampleSchema (utils.js:608)
    at t.value (response.jsx:113)
    at t.render (root-injects.js:93)
    at u._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:796)
    at u._renderValidatedComponent (ReactCompositeComponent.js:819)
    at u.performInitialMount (ReactCompositeComponent.js:359)
    at u.mountComponent (ReactCompositeComponent.js:255)

We saw this problem begin when we upgraded to Nest 5.0.0

@chadjaros I'm seeing this problem with Nest 4 as well. Are you able to confirm things still work for your previous versions?

But now we have another issue: @ApiBearerAuth doesn't do a thing! It worked previously but suddenly it stopped.

@alexandr2110pro track this issue here https://github.com/nestjs/swagger/issues/83

The rest should be fixed in 2.0.1 which I just published.

any updates for this issue, I have the same problem

export class JobListDto {
  @ApiModelPropertyOptional()
  user: string[]

  @ApiModelPropertyOptional()
  status: string[]

  @ApiModelPropertyOptional()
  software: string[]

  @ApiModelPropertyOptional()
  dates: number[]
}

@Get('execl')
  async execl(@Query() query: JobListDto, @Res() res: Response) {
    const data = await this.jobService.excelData(query)
    res.setHeader('Content-Type', 'application/vnd.openxmlformats')
    res.setHeader(
      'Content-Disposition',
      `attachment; filename=job_${new Date().toISOString()}.xlsx`,
    )
    res.end(data, 'binary')
  }

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ericzon picture ericzon  路  4Comments

patilrevansidh picture patilrevansidh  路  4Comments

Fiorello picture Fiorello  路  5Comments

dennisameling picture dennisameling  路  4Comments

mogusbi picture mogusbi  路  3Comments