'NestJS and Prisma ORM : cleanest way to exclude password from response while allow it in requests?

I'm using NestJS with Prisma ORM and kinda of struggling with the use of @Exclude() decorator because when I add it on my UserDto, it also excludes the password from the incoming requests, so Prisma does not access to the password.

For now, I've done this, but I'm sure it is not the cleanest way to do it.

User DTO

export class CreateUserDto {
  // [...]

  // Not @Exclude() here because otherwise I don't get Passwords from Incoming requests
  @IsString()
  @IsNotEmpty()
  password: string;
}

export class UserDto extends CreateUserDto {

  @Exclude()
  password: string;
}

User Service

  // [...]
  async create(userData: CreateUserDto): Promise<User> {
    userData.password = await argon.hash(userData.password);

    try {
      const createdUser = await this.prismaService.user.create({
        data: userData,
      });

      // *** DIRTY PART ***
      return plainToClass(UserDto, createdUser) as User;
      // *** DIRTY PART ***
    } catch (e) {
      if (e instanceof Prisma.PrismaClientKnownRequestError) {
        if (e.code === 'P2002')
          throw new ConflictException('A user with this email already exists');
      }

      throw e;
    }
  }
  // [...]

User Controller

  // [...]
  @Post('register')
  async register(@Body() userData: CreateUserDto) {
    console.log(userData);
    return this.userService.create(userData);
  }
  // [...]

Thanks for your answers!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source