NestJS dependency injection

Viewed 59

I have a service that consumes messages from a queue and depending on type in the message I want to init a service. For example for a message { "type": "A" } I want to use ServiceA, for a message { "type": "B" } I want to use ServiceB. Both ServiceA and ServiceB extends abstract BaseService.

How can I inject NestJS Injectable into ServiceA?

2 Answers

For example you have methods in you service that you want to use in your controller with requests methods.

I used it this way:

in user.service.ts

    @Injectable()
    export class UserService {  

    public getAllUsers(): Promise<User[]> {
      return User.find();
    }

and you Inject it inside Controller with @Inject() decorator like so:

in user.controller.ts

    @Controller('users')
    export class UserController {
      constructor(
        @Inject(UserService) private readonly userService: UserService,
      ) {}

and now you can use UserService methods in your UserController e.g.:

    @Get()
    public getAllUsers(): Promise<User[]> {
      return this.userService.getAllUsers();
    }

Remember to import all required decorators (@Inject, @Injectable, @Get etc.)

Eventually, both services must be initialized so you could refer to the in the runtime. I would recommend you create a common custom provider that aggregates all these handler services together and provide it to the module. This way you could inject this custom provider only and have all the handlers available.

//provider

@Injectable()
export class HandlerService {
    constructor(private handlers: BaseService[]) {}

    public handle(message: any): any {
        // define your handler logic here and apply handler from the handlers array
    }
}

//module

@Module({
    providers: [
        ServiceA,
        ServiceB,
        {
          provide: 'HANDLER_SERVICE',
          useFactory: (...handlers) => new HandlerService(handlers),
          inject: [ServiceA, ServiceB],
        },
    ],
})

Related