Ashish Choubey
Ashish Choubey

Reputation: 457

DTO in nest js accepting more parameter as compared to DTO

I have a DTO


export class UpdateUserRoleDTO {
  @ApiProperty()
  @IsNotEmpty()
  readonly userId:number;

  @ApiProperty()
  @IsNotEmpty()
  @IsNumber()
  readonly roleId: number;
}

My controller looks like this

@UsePipes(new ValidationPipe())
  @Post('/update')
  async updateUser(@Body() updateUserDto: UpdateUserDTO): Promise<User> {
    return await this.userService.updateUser(updateUserDto);
  }

Whenever client sends a request with the following payload

payloadObj = {
   userId : 1,
   roleId : 1,
   xyz : 'assddcds',
   someotherkey : 'fsdvs'
}

It's hitting my service file .I want to avoid this make sure only parameter mentioned in DTO should be passed else it should give 400

Upvotes: 2

Views: 2542

Answers (1)

A. Maitre
A. Maitre

Reputation: 3559

given your code I'd pass the whitelist option set to true to the ValidationPipe you're instantiating, like so in your controller:

controller.ts

@UsePipes(new ValidationPipe({ whitelist: true }))
@Post('/update')
async updateUser(@Body() updateUserDto: UpdateUserDTO): Promise<User> {
  return await this.userService.updateUser(updateUserDto);
}

This should do the work.

Let me know if it helps, otherwise don't hesitate to comment & share your findings ;)

Upvotes: 2

Related Questions