Serialization: How to exclude Entity columns in json response but not internal queries in Nestjs
You can skip properties depending on the operation. In your case, you would use:
@Column()
@Exclude({ toPlainOnly: true })
password: string;
This means, that password is only skipped when a class is transformed to json (when you send a response) and not when json is transformed to a class (when you get a request).
Then add the @UseInterceptors(ClassSerializerInterceptor)
to your controller or a controller method. This will automatically transform an entity class to json, when you return it.
For the ClassSerializerInterceptor
to work, make sure that your entity was transformed to a class first. This can be automatically done by using the ValidationPipe
with the { transform: true}
option or by returning an entity from a repository (database). Also, you have to return the entity itself:
@Post()
@UseInterceptors(ClassSerializerInterceptor)
addUser(@Body(new ValidationPipe({transform: true})) user: User) {
// Logs user with password
console.log(user);
// Returns user as JSON without password
return user;
}
Otherwise, you have to transform it manually:
async profile(@Request() req: IUserRequest) {
// Profile comes from the database so it will be an entity class instance already
const profile = await this.authService.getLoggedInProfile(req.user.id);
// Since we are not returning the entity directly, we have to transform it manually
return { profile: plainToClass(profile) };
}