Import a module which has a dynamic module as dependency in nest.js

5.7k views Asked by At

I'm newbie in nest.js and i'm trying to use a service from Q module in APP module. Q module is importing a dynamic BullModule for Queue ...

q.module.ts

import { BullModule } from '@nestjs/bull';
import { Module } from '@nestjs/common';
import { join } from 'path';
import { QService } from './q.service';

@Module({
  imports: [
    BullModule.registerQueue({
      name: 'volume',
      processors: [
        {
          name: 'create',
          path: join(__dirname, 'vol.processor.js'),
        },
      ],
    }),
  ],
  providers: [QService],
})

app.module.ts

const ENV = process.env.NODE_ENV;
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: !!ENV ? `.env.${ENV}` : '.env',
    }),
    BullModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        redis: {
          host: configService.get('REDIS_HOST'),
          port: Number(configService.get('REDIS_PORT')),
          password: configService.get('REDIS_PASSWORD'),
        },
      }),
      inject: [ConfigService],
    }),
    IdentityModule,
    QModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    IdentityService,
    QService,
  ],
})
export class AppModule {}

Nest says:

Nest can't resolve dependencies of the QService (?). Please make sure that the argument BullQueue_volume at index [0] is available in the AppModule context.

Potential solutions:
- If BullQueue_volume is a provider, is it part of the current AppModule?
- If BullQueue_volume is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing BullQueue_volume */ ]
  })

How i can handle this? I read some docs but i can't find :(

1

There are 1 answers

0
Jay McDoniel On BEST ANSWER

Rather than redefining QService in AppModule's providers, QModule should have QService in both providers and exports. This will allow any module that imports: [QModule] to make use of the exports of QModule without needing to redefine the provider.

As a side note, every time you add a provider to the providers array of a module, that will be a new instance of said provider. In this case, there's two instances, and the AppModule wants access to everything QService needs. This is why you should use exports instead.