Is it possible to use the ValidationPipe with whiteList on response body?

I’d like to prevent returning of object key values on responses of NestJs server (and using TypeOrm entity in the example)

For example, I’d like to make sure that a user’s password will never be sent to any client:

user.entity.ts:

@Entity()
export class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  password: string;
}

user.controller.ts:

  @Get('')
  getAllUsers(): Promise<User[]> {
      return this.userService.getAll(); // expected: [{id: 1}], actual: [{id: 1, password: '1234'}]
  }

I that can be implemented for requests body by using class-validator pipe:

  new ValidationPipe({
      whitelist: true
  })

user.dto.ts:

export class UserDto {
  @Allow()
  id: number;

  password: string;
}

Can that type of key’s filtration possible with the ValidationPipe?
Is there any other elegant solution for that?

1 thought on “Is it possible to use the ValidationPipe with whiteList on response body?”

Leave a Comment