【问题标题】:How do you inject a service in NestJS into a typeorm repository?如何将 NestJS 中的服务注入 typeorm 存储库?
【发布时间】:2020-06-06 10:17:47
【问题描述】:

我有一个UserRepository,它处理在数据库前面创建/验证用户。我想对用户的密码进行哈希和验证,所以我为此创建了一个单独的服务,试图遵循单一责任原则,声明如下:

@Injectable()
export default class HashService

然后我将它导入到我的模块中:

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

我希望将它注入UserRepository,我尝试将它作为构造函数参数传递,但它不起作用,因为它的基类已经接受了那里的 2 个参数,所以我尝试像这样在它们之后注入我的服务:

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

    // Logic...
}

hashService 未定义,我也尝试不使用@Inject() 装饰器。 将HashService 注入我的存储库的最佳方法是什么?我必须创建它的新实例吗?

【问题讨论】:

    标签: typescript nestjs typeorm


    【解决方案1】:

    您可以像这样从模块服务手动添加它:

    askers.service.ts:

    constructor(
        @InjectRepository(AskersRepository)
        private repository: AskersRepository,
        private logger: LoggingService,
    ) {
        this.repository.logger = logger;
    }
    

    askers.repository.ts:

    logger: LoggingService;
    

    然后记录器服务将在存储库中可用,就像它已被注入一样。

    【讨论】:

    • 这个实现就像 DI 一样,谢谢。
    【解决方案2】:

    您还可以从实例化存储库的主服务中分配特定服务的实例。

    A.目录.service.ts

    @Injectable()
    export class CatalogService {
        constructor (
            private readonly cacheService: CacheService,
            public readonly catalogRepository: CatalogRepository
        ) {
            this.catalogRepository.cacheService = this.cacheService;
        }
    }
    

    B.目录.repository.ts

    @EntityRepository(CatalogEntity)
    export class CatalogRepository extends Repository<CatalogEntity> {
        cacheService: CacheService;
        cacheExpirySeconds = 60*60;
    }
    
    

    【讨论】:

      【解决方案3】:

      简短的回答:你不知道。

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

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

      【讨论】:

        猜你喜欢
        • 2019-07-05
        • 2021-07-15
        • 2022-09-24
        • 2019-08-17
        • 2021-11-21
        • 2020-04-19
        • 2022-09-23
        • 2021-01-07
        • 2022-08-05
        相关资源
        最近更新 更多