小编zor*_*orn的帖子

NestJS:将服务注入模型/实体

我目前被困在一个问题上,我不知道如何解决:

在我的 NestJS 应用程序中,我想让我的所有TypeORM Entities扩展BaseEntity类都提供一些通用功能。例如,我想提供一种额外的getHashedID()方法来散列(并因此隐藏)我的 API 客户的内部 ID。

散列是由 a 完成的HashIdService,它提供了一个encode()anddecode()方法。

我的设置看起来像这样(删除了装饰器以提高可读性!):

export class User extends BaseEntity {
  id: int;
  email: string;
  name: string;
  // ...
}

export class BaseEntity {
  @Inject(HashIdService) private readonly hashids: HashIdService;

  getHashedId() {
    return this.hashids.encode(this.id);
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我调用该this.hashids.encode()方法,它会抛出一个异常:

Cannot read property 'encode' of undefined
Run Code Online (Sandbox Code Playgroud)

我怎样才能把inject一个服务变成一个entity/model类?这甚至可能吗?

更新 #1 特别是,我想“注入”HashIdService到我的Entities. 此外,Entities应该有一个 …

entity dependency-injection nestjs

9
推荐指数
1
解决办法
2399
查看次数

标签 统计

dependency-injection ×1

entity ×1

nestjs ×1