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

时间:2018-11-23 09:10:12

标签: dependency-injection entity nestjs

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

在我的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归类?这有可能吗?

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

非常感谢您的帮助!

2 个答案:

答案 0 :(得分: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;
    }
}

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 = 'tony.stark@avenge.com';

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

答案 1 :(得分:0)

我找到的解决方案是:

在配置服务中,使用:

constructor(filePath: string) {
    const dotenvPath = path.join(__dirname, '../../env', filePath);
    const config = dotenv.parse(fs.readFileSync(dotenvPath, 'utf8'));
    dotenv.config({
        path: dotenvPath,
    });
    this.envConfig = this.validateInput(config);
}

dotenv.config部分将设置process.env中env文件中的所有变量,然后在util函数中使用它们。

相关问题