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?
AFIK
ValidationPipe
is there to validate incoming requests.You should define a serialization interceptor to proper remove the keys that you don’t want to return. With this setup, you don’t need to validate that DTO.