lundi 13 décembre 2021

What is the best pattern for Serialization in NestJS Response DTO?

User entity has 'id', 'email' and 'password'. When create, I want to returned only the created 'id' and 'email'.

  async createUser(email: string, password: string) {
    const createdUser = await this.userRepository.save({ email, password });

    return { id: createdUser.id, email: createdUser.email };
  }

Currently, the service layer is using it as above. But I think this is like an anti-pattern, Because it is not a NestJS pattern.

If so, is it best to define the DTO(SerializationUserDto) and use it as follows in the controller layer? Or is there a better pattern?

export class SerializationUserDto {
  @Exclude() private readonly user;

  constructor(user: User) {
    this.user = user;
  }

  @ApiProperty()
  @Expose()
  get id(): number {
    return this.user.id;
  }

  @ApiProperty()
  @Expose()
  get email(): string {
    return this.user.email;
  }
}
const user = this.userService.createUser(email, password);

return new SerializationUserDto(user);

Aucun commentaire:

Enregistrer un commentaire