Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nestjs global pubsub instance and dependency injection

I followed the Nestjs DOCS regarding pubsub/subsciprtions:

According to the examples, pubsub is initialized at the top of a given resolver with:

const pubSub = new PubSub();

later the docs say:

"We used a local PubSub instance here. Instead, we should define PubSub as a provider, inject it through the constructor (using @Inject() decorator), and reuse it among the whole application"

{
  provide: 'PUB_SUB',
  useValue: new PubSub(),
}

where does this go though?
I.e. what's the syntax/approach for how to provide this in my main app.module so it's available in all other modules?

if i try to provide this as a dependency in a different module i'm getting dependency resolution issues. app.module

  providers: [
    AppService,
    {
      provide: APP_FILTER,
      useClass: AllExceptionsFilter,
    },
    {
      provide: 'PUB_SUB',
      useValue: new PubSub(),
    },

some-resolver.js

  constructor(
    @Inject('PUB_SUB')
    private pubSub: PubSub,

gives: Nest can't resolve dependencies of the MyResolver ( MyResolver is provided by MyModule

I can't import appmodule into MyModule or i'll create a circular depenency.

Do i define a new module which just provides a pub_sub instance?

like image 987
baku Avatar asked Nov 29 '19 12:11

baku


1 Answers

If you're looking for it to easily be available to all your other modules, I would suggest creating a PubSubModule that provides your PubSub and exports it if you want to have to import the module, or just has the module marked as @Global() so the PubSub can be injected anywhere

Exports Method

@Module({
  providers: [
    {
      provide: 'PUB_SUB',
      useClass: PubSub,
      // useValue: new PubSub(),
      // useFactory: () => {
      //  return new PubSub();
      // }
    }
  ],
  exports: ['PUB_SUB'],
})
export class PubSubModule {}

Global Method

@Global()
@Module({
  providers: [
    {
      provide: 'PUB_SUB',
      useClass: PubSub,
      // useValue: new PubSub(),
      // useFactory: () => {
      //  return new PubSub();
      // }
    }
  ],
})
export class PubSubModule {}
like image 77
Jay McDoniel Avatar answered Nov 15 '22 05:11

Jay McDoniel