【问题标题】:NestJS - Transform DTO data to EntityNestJS - 将 DTO 数据转换为实体
【发布时间】:2022-01-10 03:09:00
【问题描述】:

我有一个像这样的简单用户实体:

@Entity('users')
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({ unique: true })
    email: string;

    @Column()
    passwordHash: string;
}

这是 CreateUserDto 类:

export class CreateUserDto {
   @IsEmail()
   email: string

   @IsNotEmpty()
   password: string
}

我想保留CreateUserDto 中的password 字段并自动映射到User 实体类中的passwordHash。那么我该怎么做呢?请帮我。非常感谢!

【问题讨论】:

    标签: node.js nestjs


    【解决方案1】:

    NestJS 没有自动映射之类的东西。所以你有两个选择:

    1. 创建user.service.ts 并在其中对密码进行映射+哈希处理。
    create(dto: CreateUserDto) {
      const user = new User();
      user.email = dto.email;
      user.password = createPasswordHash(dto.password); // createPasswordHash fucntion needs to be defined
    }
    
    1. 使用提供自动映射功能的第三方库,例如 AutoMapper TypeScript(还有 out-of-the-box NestJS support)。

    如果有大型 DTO 需要映射 (2.),我建议使用 Automapper,否则我会手动进行映射 (1.)。

    【讨论】:

    • 谢谢,但我想像这样发送请求数据: {“email”: “abc@mail.test”, “password”: “abc” } 它会自动映射到实体,例如这个:新用户(电子邮件:“abc@mail.test,密码哈希:“abc”)
    • 也许你想要一个转换管道? docs.nestjs.com/pipes#transformation-use-case 否则,如果您提供一个带有最小示例的 CodeSandbox,将会很有帮助。
    猜你喜欢
    • 2021-12-15
    • 2019-04-22
    • 2020-07-23
    • 2016-06-10
    • 1970-01-01
    • 2019-05-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多