Danagon
Danagon

Reputation: 407

NestJS only apply ClassSerializerInterceptor to response data

I have a question about the ClassSerializationInterceptor in NestJS. Right now I use it to remove the password when returning user data, like the example given in the NestJS documentation (https://docs.nestjs.com/techniques/serialization). When I return a user the password property gets removed (this part is working). However, when I create a new user (and have a password property in the request body) the request body gets serialized as well, with the result that the following validation pipe complains about the password field missing. Is it possible to apply this interceptor just to the response data?

My controller method looks like this:

@UsePipes(new ValidationPipe({ transform: true })
@UseInterceptors(ClassSerializationInterceptor)
@Post()
async add(@Body() userData: User) {
  return this.userService.addUser(userData)
}

My user entity looks like this:

@Entity()
@Unique['email']
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  email: string;

  @Column()
  @Exclude()
  password: string;
}

The code is simplified, but enough to reproduce the problem/this behaviour.

Upvotes: 0

Views: 3834

Answers (1)

Natan Deitch
Natan Deitch

Reputation: 622

nest uses class-transformer to do it.

Class transformer do serialization in both ways:

  • Plain to class (JSON to Class instance)
  • Class to plain (Class instance to JSON)

So you can try pass toPlainOnly: true to exclude decorator:

@Entity()
@Unique['email']
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  email: string;

  @Column()
  @Exclude({ toPlainOnly: true })
  password: string;
}

Class transformer doc

Upvotes: 2

Related Questions