LuxProt
LuxProt

Reputation: 21

How can I filter out excess model property

I have a DTO object like this:

export class CreateProductDTO {
  readonly _id: number;
  readonly _name: string;
  readonly _price: number;
}

The DTO is used at my post method

@Post('users')
async addUser(@Response() res, @Body(new ValidationPipe()) createUserDTO: CreateUserDTO) {
    await this.userService.addUser(createUserDTO).subscribe((users) => {
        res.status(HttpStatus.OK).json(users);
    });
}

When I post json data, it will serialize to CreateProduceDTO obcjet

{
  "_id":1,
  "_name":"Lux",
  "_age":19
}

But I post json data with excess property, it also serialize to CreateProduceDTO obcjet with excess property

{
  "_id":1,
  "_name":"Lux",
  "_age":19,
  "test":"abcv"
}

CreateUserDTO { _id: 1, _name: 'Lux', _age: 19, test: 'abcv' }

I had tried to filter it with pipe, but I have no idea. Thanks all.

Upvotes: 2

Views: 3389

Answers (1)

Valera
Valera

Reputation: 2943

If you want to just remove the excess properties, you can use ValidationPipe like this :

new ValidationPipe({whitelist: true})

If you would rather to have an error thrown when any non-whitelisted properties are present:

new ValidationPipe({whitelist: true, forbidNonWhitelisted: true})

Check out https://www.npmjs.com/package/class-validator#whitelisting for more options

Upvotes: 7

Related Questions