Jor*_*rdi 2 node.js typescript nestjs
我目前正在使用 TypeOrm 完成 NestJS 的数据库集成文档。在这些文档中,有一些示例展示了如何使用 NestJS 中的 app.module 注入自定义数据库存储库。所有这些示例都使用自定义存储库的实际类型注入类。
@Injectable()
export class AuthorService {
constructor(private authorRepository: AuthorRepository) {}
}
Run Code Online (Sandbox Code Playgroud)
此代码通过 app.modules 提供如下导入来注入:
@Module({
imports: [TypeOrmModule.forFeature([AuthorRepository])],
controller: [AuthorController],
providers: [AuthorService],
})
export class AuthorModule {}
Run Code Online (Sandbox Code Playgroud)
如果您擅长针对实现进行编程,那么这很有效,但我更喜欢在我的类中使用接口。我已经在上一个问题中找到了通过 NestJS 接口注入类的解决方案,但是当我尝试像这样注入自定义存储库时,它似乎没有正确实例化并且变得未定义。
(node:16658) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'save' of undefined
因此,我假设您只能通过forFeature()app.module 中的调用注入 customRepositories,但据我所知,这不允许我使用接口进行注入。有没有其他方法可以注入自定义 TypeOrm 存储库,而无需替换所有接口来实现自定义存储库?提前致谢!
编辑
这是我当前的代码,我设法将其注入,但这仍然迫使我在每次调用构造函数时使用实现而不是接口。这主要是由于模拟而进行测试时出现的问题。
@CommandHandler(FooCommand)
export class FooHandler
implements ICommandHandler<FooCommand> {
private fooRepository: IFooRepository; // Using Interface as a private property.
private barEventBus: IEventBus;
constructor(fooRepository: FooRepository,
barEventBus: EventBus) { // Forced to use implementation in constructor for injection.
this.fooRepository = fooRepository;
this.barEventBus = barEventBus;
}
Run Code Online (Sandbox Code Playgroud)
@EntityRepository(FooEntity)
export class FooRepository extends Repository<FooEntity> implements IFooRepository {
getFoo() {
// Do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
@Module({
imports: [TypeOrmModule.forRoot(), TypeOrmModule.forFeature([FooRepository]],
// Other module setup
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
它应该与使用装饰器一起使用,InjectRepository您在其中指定存储库,但然后您键入 is 作为您的界面,并且在测试时您只需提供IFooRepository!
示例代码:
constructor(@InjectRepository(FooRepository) fooRepository: IFooRepository,
barEventBus: EventBus) {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17779 次 |
| 最近记录: |