【问题标题】:NestJS : Inject Service into Models / EntitiesNestJS:将服务注入模型/实体
【发布时间】:2019-04-25 21:12:07
【问题描述】:

我目前遇到一个问题,我不知道如何正确解决:

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

哈希由HashIdService 完成,它提供encode()decode() 方法。

我的设置如下所示(为了可读性删除了装饰器!):

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);
  }
}

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

Cannot read property 'encode' of undefined

我如何将inject 服务转换为entity/model 类?这甚至可能吗?

更新 #1 特别是,我想将HashIdService“注入”到我的Entities 中。此外,Entities 应该有一个 getHashedId() 方法返回它们的散列 ID。因为我不想“一遍又一遍”地这样做,我想在 BaseEntity 中“隐藏”这个方法如上所述..

我目前的 NestJS 版本如下:

Nest version:
+-- @nestjs/common@5.4.0
+-- @nestjs/core@5.4.0
+-- @nestjs/microservices@5.4.0
+-- @nestjs/testing@5.4.0
+-- @nestjs/websockets@5.4.0

非常感谢您的帮助!

【问题讨论】:

  • 为什么有必要注入这个特定的服务而不是仅仅引用一个实用函数?
  • @JesseCarter 也许它需要访问数据库之类的东西,否则会被注入?
  • @JesseCarter 我刚刚更新了我最初的问题。我想注入HashIdService,以便我的实体能够散列他们自己的ID。你将如何解决这个问题? “实用功能”是什么意思?
  • 如果要在模型中使用,需要手动设置服务。
  • 您是否考虑过扩展 BaseEntity,然后使用扩展版本?

标签: dependency-injection entity nestjs


【解决方案1】:

如果您不需要注入 HashIdService 或在单元测试中模拟它,您可以简单地这样做:

BaseEntity.ts

import { HashIdService } from './HashIdService.ts';

export class BaseEntity {

    public id: number;

    public get hasedId() : string|null {
        const hashIdService = new HashIdService();
        return this.id ? hashIdService.encode(this.id) : null;
    }
}

用户.ts

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

然后创建你的用户:

const user = new User();
user.id = 1234;
user.name = 'Tony Stark';
user.email = 'tony.stark@avenge.com';

console.log(user.hashedId);
//a1b2c3d4e5f6g7h8i9j0...

【讨论】:

  • 如果HashIdService 也有 DI 链,这将变得非常困难/不可能。
猜你喜欢
  • 2020-09-09
  • 2022-09-24
  • 2018-11-16
  • 1970-01-01
  • 2020-06-02
  • 1970-01-01
  • 2020-07-08
  • 2019-01-20
  • 1970-01-01
相关资源
最近更新 更多