NestJS class-transformer 忽略 TypeORM-Entity 上的 Declorators

NestJS class-transformer ignoring Declorators on TypeORM-Entity

我正在尝试在 NestJS 项目中的 TypeORM 实体上使用 classToPlain,而 class Transformer 只是忽略了 @Exclude Declorator。以下是我的一些代码片段:

user.entity

@Entity()
export class User {
  @Column()
  @Exclude()
  password!: string;
}

export const userToPlain = (user : User) => {
  return classToPlain<User>(user);
}

user.service

  createUser(userDTO : userCreateDTO, role?: RoleType[]) : Promise<User> {
    return new Promise<User>(async (resolve, reject) => 
      this.usersRepository.save(userDTO).then(res => {
        resolve(res);
      }).catch(reject);
    })
  }

users.controller

@Post("/create")
create(@Body() userDto : userCreateDTO, @Req() request: Request, @Res() res: Response) {
      this.userService.createUser(userDto, ["EDITOR"]).then(newUser => {
        res.status(201);
        res.json(userToPlain(newUser));
      })
  })
}

我之前既没有使用过 NestJS、TypeORM 也没有使用过 class-transformer,所以我真的不知道发生了什么。

在此先致谢并致以亲切的问候。

您正在将 @Res() 注入您的路由处理程序。 Nest 的文档 explicitly state that if you use @Res() you are in charge of formatting and sending the response yourself. If you want Nest to handle the response for you, remove @Res() from the route handler, and use @UseInterceptors(ClassSerializationInterceptor) as described in the docs here

编辑 8/3/21 回答问题

抱歉,我看问题太快了,没有注意到你确实在调用res.senduserToPlain方法。

所以,TypeORM 的 save 方法有点奇怪,因为它只是 returns 一个对象,而不是 class 实例,所以关于 classToPlain 方法,因此,它 returns 对象原样。您可以通过记录 newUser instanceof User.

自行验证

你可以做的是先调用 plainToClass,这样你就可以得到 User class 的实际实例,然后可以在 userToPlain方法。你可以把它放在你的 useToClass 方法中,或者让它成为 UserService#createUser

的一部分