I recently came across a unique situation. I am using NestJS, TypeOrm and Postgres.
I have a DynamicModule called CoreModule that is registered in the AppModule as following:
@Module({
imports: [
...,
CoreModule.register(),
...,
]
})
This core module registers some typeorm entities and repositories (custom, in a separate file) as following:
export class CoreModule {
static register(): DynamicModule {
return {
module: CoreModule,
imports: [
...,
TypeOrmModule.forRootAsync({
...,
}),
TypeOrmModule.forFeature([
ARepository,
BRepository,
CRepository,
AEntity,
BEntity,
CEntity,
]),
],
exports: [TypeOrmModule],
};
}
}
The repositories I created look like this (I followed this stackoverflow answer How to create custom (separate file) repository in NestJS 9 with TypeORM 0.3.x)
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
@Injectable()
export class ARepository extends Repository<AEntity> {
constructor(
@InjectRepository(AEntity)
private aRepository: Repository<AEntity>
) {
super(aRepository.target, aRepository.manager, aRepository.queryRunner);
}
async customFunctionA() {}
async customFunctionB() {}
}
I use this as following in one of the services:
@Injectable()
export class SomeService {
constructor(
private readonly aRepository: ARepository,
) {}
public async someFunction() {
return this.aRepository.customFunctionA();
}
Now when I try to use this CustomRepository and call aRepository.customFunctionA or aRepository.customFunctionB I get an error this.aRepository.customFunctionA is not a function. I checked and found that this.aRepository has only has only three properties (target, manager and queryRunner) I think these come from Repository that I extend but none of the custom function I define in the repository are there.
Furthermore, if I remove the ARepository from TypeOrmModule.forFeature([]) argument array and add it to all modules that use it in like a normal injectable class, it works fine (I see custom functions).
My question is, why is doing TypeOrmModule.forFeature([]) not working here, what am I doing wrong and what should be avoided with forFeature in future?
I have found a solution as mentioned above in my explanation but do not understand why the initial code doesn’t work and if there is a better way to solve it.