#InjectRepository with dynamics

2 messages · Page 1 of 1 (latest)

wooden barn
#

Hi, can I somehow Inject repository with Generic type? Also, this is maybe a typescript question but what is the appropriate way to combine injectable params and some other that are required to be passed by each class that extends that class. Can I put them as optional?
I am trying to create some base CacheService. This is example:
`@Injectable()
export class CacheService<T extends EntityClassOrSchema> {
constructor(
private readonly key: string,
@Inject(CACHE_MANAGER) private cacheManager?: Cache,
@InjectRepository(T) private readonly repository?: Repository<T>){
}

async get(){
    const existingData = await this.cacheManager.get(this.key);
    if(!existingData){
        const dbData = await this.repository.find();
        await this.set(dbData);
        return dbData;
    }

    return existingData;
}

and then I want to use it as follows:@Injectable()
export class AppInfoService extends CacheService<AppInfo> {
constructor(){
super('APP_INFO');
}
}`
but I am getting the error: 'T' only refers to a type, but is being used as a value here.ts inside CacheService

covert snow
#

Generics don't exist at runtime, so there's no way to pass T to the @InjectRepository(). You need to use a mixin so you can do something like AppInfoService extends CacheService(AppInfo) {}