Search code examples
nestjstypeorm

How to create service with Repository exports?


I created service with several repository:

@Injectable()
export class DataService {
    constructor(
        @InjectRepository(ClassicPrices, 'connect')
        private classicPrices: Repository<ClassicPrices>,

        @InjectRepository(ModernPrices, 'connect')
        private modernPrices: Repository<ModernPrices>,
    ) {}

    public pricesRepository(server): Repository<ModernPrices | ClassicPrices> {
        switch (server) {
            case 'modern':
                return this.modernPrices;
            case 'classic':
                return this.classicPrices;
        }
    }
}

Data module settings:

@Module({
  imports: [
    TypeOrmModule.forFeature([
      ClassicPrices,
      ModernPrices
    ], 'connect'),
  ],
  providers: [DataService],
  exports: [DataService]
})
export class DataModule {}

When I use it in another modules^ I have error "Nest can't resolve dependencies of the DataService (connect_ClassicPrices). Please make sure that the argument connect_ClassicPrices at index [2] is available in the DataModule context.

Potential solutions:

  • If connect_ClassicPrices is a provider, is it part of the current DataModule?
  • If connect_ClassicPrices is exported from a separate @Module, is that module imported within DataModule?
  @Module({
    imports: [ /* the Module containing  connect_ClassicPrices */ ]
  })

How to export repository ?


Solution

  • If you want to use a repository from DataModule in other modules you need to add TypeOrmModule to the exports array in DataModule:

    exports: [DataService, TypeOrmModule]
    

    Then, any module that imports DataModule can use the repositories registered with TypeOrmModule.forFeature. Generally it's a better practice to export just the services and keep the repositories scoped to their module because that makes your app more modular.