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

问题描述 投票:3回答:1

我目前陷入一个问题,我不知道该如何解决:

在我的NestJS应用程序中,我想使我的所有TypeORM Entities扩展一个BaseEntity类,该类提供一些常规功能。例如,我想提供一种附加的getHashedID()方法,该方法对我的API客户的内部ID进行哈希处理(并因此隐藏)。

通过HashIdService进行哈希处理,它提供了encode()decode()方法。

我的设置看起来像这样(为了方便阅读,删除了Decorators!):

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类?这甚至可能吗?

UPDATE#1特别是,我想将HashIdService“注入”到我的Entities中。此外,Entities应该具有返回其哈希ID的getHashedId()方法。由于我不想“一遍又一遍”执行此操作,因此我想在“ BaseEntity”中“隐藏”此方法如上所述。

我当前的NestJS版本如下:

Nest version:
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]

非常感谢您的帮助!

dependency-injection entity nestjs
1个回答
0
投票

如果您不需要注入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;
    }
}

User.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 = '[email protected]';

console.log(user.hashedId);
//a1b2c3d4e5f6g7h8i9j0...
© www.soinside.com 2019 - 2024. All rights reserved.