How do you inject a service in NestJS into a typeorm repository?

DaC*_*rse 9 typescript typeorm nestjs

I have a UserRepository which handles creating/authenticating users infront of the database. I want to perform hashing & validation for the user's password, so I created a seperate service for that purpose, trying to follow single repsonsibility principle, which is declared like this:

@Injectable()
export default class HashService
Run Code Online (Sandbox Code Playgroud)

And I import it in my module:

@Module({
    imports: [TypeOrmModule.forFeature([UserRepository])],
    controllers: [AuthController],
    providers: [AuthService, HashService],
})
export class AuthModule {}
Run Code Online (Sandbox Code Playgroud)

I wish to inject it into UserRepository, I tried passing in it as a constructor parameter but it didn't work because it's base class already accepts 2 parameters there, so I tried injecting my service after them like so:

@EntityRepository(User)
export default class UserRepository extends Repository<User> {
    constructor(
        entityManager: EntityManager,
        entityMetadata: EntityMetadata,
        @Inject() private readonly hashService: HashService,
    ) {
        super();
    }

    // Logic...
}
Run Code Online (Sandbox Code Playgroud)

But hashService was undefined, I also tried without the @Inject() decorator. What would be the best way to inject HashService into my repository? Do I have to create a new instance of it?

Jay*_*iel 8

简短的回答:你没有。

TypeORM 的自定义存储库、存储库类和实体在技术上处于 Nest 的 DI 系统之外,因此不可能向其中注入任何值。如果你真的想要去做,你可以弄清楚一个Repository类需要什么它的构造函数参数并将它们添加到工厂以实例化存储库类并直接使用它而不是通过TypeOrmModule.forFeature,但这是相当多的额外工作。

在我看来,自定义存储库模式在 Nest 中并没有太大帮助,因为服务本质上持有将要实现的逻辑CustomRepository。存储库类是您通往数据库的门户,但不需要向其中添加任何额外的逻辑。