gpt4 book ai didi

javascript - 无法注入(inject)自定义存储库

转载 作者:行者123 更新时间:2023-12-01 01:00:40 24 4
gpt4 key购买 nike

我想使用请求范围的缓存来支持我的存储库,类似于 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];
}
}

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

@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;

}

}

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

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

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

最佳答案

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

@Injectable()
export class EnqueuedRepository {
@Inject() readonly cache: RequestScopedCache;

constructor(
@InjectRepository(Enqueued) private readonly enqueuedRepository: Repository<Enqueued>
) {
}
}

关于javascript - 无法注入(inject)自定义存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56110035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com