Trung BìnhNestJS iconNestJS

Serialization và response transformation với class-transformer trong NestJS?

class-transformer cùng với ClassSerializerInterceptor tự động serialize/exclude fields trong response.

Exclude sensitive fields (password, tokens):

typescript
import { Exclude, Expose, Transform } from 'class-transformer';

export class UserEntity {
  id: number;
  email: string;

  @Exclude()  // Không expose trong response
  password: string;

  @Expose()
  @Transform(({ value }) => value?.toISOString())
  createdAt: Date;

  constructor(partial: Partial<UserEntity>) {
    Object.assign(this, partial);
  }
}

Enable globally:

typescript
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));

Controller return entity:

typescript
@Get(':id')
async findOne(@Param('id') id: number): Promise<UserEntity> {
  const user = await this.usersService.findOne(id);
  return new UserEntity(user);  // Wrap trong entity class
}

Pitfall: plain objects không bị transform — phải trả về instance của entity class để decorator có effect.

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS