Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

nestjs - 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 ?

question from:https://stackoverflow.com/questions/65934094/how-to-create-service-with-repository-exports

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...