【问题标题】:Can't inject custom repository无法注入自定义存储库
【发布时间】:2019-09-30 06:39:46
【问题描述】:

我想用请求范围的缓存来支持我的存储库,类似于 Hibernate 的first-level-cache。我有一些关于如何做到这一点的想法,并将其与typeorm-transactional-cls-hooked 联系起来。

同时,我创建了如下简单的提供者:

@Injectable({ scope: Scope.REQUEST })
export class RequestScopedCache extends Object {

  private storage: any = {};

  public set(key: string, value: any) {
    this.storage[key] = value;
  }

  public get(key: string) {
    return this.storage[key];
  }
}

我想将它注入到我的自定义存储库中:

@Injectable()
@EntityRepository(Enqueued)
export class EnqueuedRepository extends Repository<Enqueued> {

  @Inject() readonly cache: RequestScopedCache;

  public async get(id: string) {
    const key = `${this.constructor.name}_${id}`;
    const result = this.cache.get(key);
    if (result) {
      return result;
    }
    const dbResult = await super.findOne(id);
    this.cache.set(key, dbResult);
    return dbResult;

  }

}

构造函数注入或属性注入都不适用于自定义存储库。看起来事情已经被连接起来,以便调用特定于 typeorm 的构造函数(这似乎是私有的)——注入的第一个参数似乎是一个连接。

然后我尝试了属性注入,但这也不起作用。

如何在自定义存储库中注入我自己的配置?

【问题讨论】:

    标签: javascript typescript express nestjs


    【解决方案1】:

    我不确定这是否完全相关,但使用自定义存储库的一种可能方法如下: 1.我创建一个自定义存储库类如下

    @Injectable()
    @EntityRepository(UserEntity)
    export class UserRepository extends Repository<UserEntity> {
     // You repo code here
     }
    
    1. 然后将其注入所需的类中,如下所示
    export class UserService {
     constructor(
       @InjectRepository(UserRepository)
       private userRepository: UserRepository,
     ) {}
    // Your code here
    }
    

    上述方法有助于覆盖默认的 TypeORM 函数并根据您的需要创建自定义函数...

    【讨论】:

    • 感谢您的回答,不过我试过了。我注意到您确实可以创建一个自定义存储库,但是如果您想将依赖项注入该自定义存储库,那是行不通的。
    【解决方案2】:

    Composition over inheritance,即包装存储库,并将其用作提供者可以在这里提供帮助:

    @Injectable()
    export class EnqueuedRepository {
        @Inject() readonly cache: RequestScopedCache;
    
        constructor(
            @InjectRepository(Enqueued) private readonly enqueuedRepository: Repository<Enqueued>
        ) {
        }
    }
    

    【讨论】:

    • 如果没有其他解决方案,我正在考虑类似的事情。谢谢。也许它也可以代理 - 自动将未实现的方法转发到底层类,或者通过魔法,或者只是通过使用一个明确连接所有内容的抽象基类。
    猜你喜欢
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2018-05-07
    相关资源
    最近更新 更多