dependency-injection - 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);
}
}
但是,如果我调用该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
非常感谢您的帮助!
解决方案
如果您不需要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...
推荐阅读
- azure - 无法将资产与 blob 关联
- c# - 在 Winforms C# 中启用拼写检查的情况下,如何在鼠标悬停在 WPF 文本框上时显示拼写错误建议弹出窗口?
- python - pandas groupby.agg 列出行为
- javafx - Javafx 按数据库值更改特定行颜色
- json - 返回 JSON 并打印出 reactJS
- javascript - 不要使用 util.inspect 记录符号
- android - 如何检查mysql数据库中的值?
- javascript - 如何在 wordpress 网站上隐藏外部 java sciprt 代码的图像
- reactjs - GraphQL Apollo:变量 $bool 的值无效“false”;预期的布尔类型;布尔值不能表示非布尔值:“false”
- sql - 如何更改列的数据类型并在 SQL 中添加外键?