Dependencies are undefined in NestJS processors - @nestjs/bull

72 Views Asked by At

I have configured queue mechanism in my bull and I can easily access the message that's sent by producers for processing. I am going to do some background processing using this information.

Issue is, I have a few services and repositories that I need to access but seems like I can't access. I had written custom consumers in NestJS where I accessed the objects from app

await app.resolve<LoggerService>(LoggerService);

where app is NestFastifyApplication

Constructor injection doesn't work in processors directly in case of Bull.

export class PromotionProcessor {

    public constructor(private readonly serviceLayer: ServiceLayer) { }


    @Process(PACKAGE_PROMOTION)
    async processMtPackagePromotion(job: Job<PackagePromotionRequest>):Promise<void> {
        const { data } = job;
        const messageData = data as unknown as PromotionRequest; 
       await this.serviceLayer.promoteToNextLifecycle(messageData.data, messageData.reqData);
    }
}

How can I use repositories and services here?

@Module({
  imports: [...APP_IMPORTS],
  controllers: [...APP_CONTROLLERS],
  providers: [...APP_PROVIDERS],
})

APP_IMPORTS has bull config, APP_PROVIDERS has all the repo and services defined

1

There are 1 best solutions below

3
Daniel Wasserlauf On

This may or may not be helpful.

To have a service injected into another class you need to declare it in a corresponding .module.ts file where the PromotionProcessor is a "provider"

EG:

import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bull';
import { ServiceLayerModule } from '../../serviceLayer/serviceLayer.module.js';
import { PromotionProcessor } from './PromotionProcessor.service.js';

@Module({
    controllers: [],
    providers: [PromotionProcessor],
    imports: [
        BullModule.registerQueue({
            name: 'myQueueName',
        }),
        ServiceLayerModule,
    ],
})
export class PromotionProcessorModule {}

Additionally the PromotionProcessorModule will need to be imported into your AppModule

Then in your file which contains the PromotionProcessor file you should be able to inject the file into the constructor.

Sometimes there might be some circular references which nest will alert you too so you can do the explict injection Like the following:

import { Inject, forwardRef } from '@nestjs/common';
export class PromotionProcessor {

    public constructor( @Inject(forwardRef(() => ServiceLayer)) private readonly serviceLayer: ServiceLayer) { }


    @Process(PACKAGE_PROMOTION)
    async processMtPackagePromotion(job: Job<PackagePromotionRequest>):Promise<void> {
        const { data } = job;
        const messageData = data as unknown as PromotionRequest; 
       await this.serviceLayer.promoteToNextLifecycle(messageData.data, messageData.reqData);
    }
}

Hopefully this helps somewhat.