microud / nest-mqtt

A MQTT module for Nest.js.
MIT License
45 stars 32 forks source link

Multiple `MqttModule.forRoot()` global instances #14

Open tukusejssirs opened 2 years ago

tukusejssirs commented 2 years ago

In my use case, I need two global MQTT clients: one using MQTT protocol, the other using websockets.

I added the following into app.module.ts:

@Module({
  imports: [
    MqttModule.forRoot({
      port: 1883,
      logger: {
        useValue: new Logger('MqttClient')
      }
    }),
    MqttModule.forRoot({
      protocol: 'ws',
      port: 4000,
      logger: {
        useValue: new Logger('MqttClientWs')
      }
    })
  ],
})

Now, in the service (@Inject(MqttService) private readonly mqttService: MqttService), how can I differentiate between them?

tukusejssirs commented 2 years ago

I think this SO answer could be implemented to add some token to create separate MqttService instances.

However, I am quite new to Nest to fully understand it. As I see it, we could add aditional, optional token property to MqttModuleOptions and MqttModuleAsyncOptions, right?

microud commented 2 years ago

NestJS use string token as the identifier of instance container(In NestJS v8 using object reference for Class Provider).

nest-mqtt using a constant key as mqtt instance token and can't extend anymore.

Add multiple instance support is easy, but this lib should add multiple client getter, operator and event identifier at the same time what may cause a breaking change.