NestJS microservices: catch broker disconnection

108 views Asked by At

In express-based applications, we can catch the broker error as following:

mqttClient.on('reconnect', () => {
    console.log('reconnecting...');
    // notify to sentry
})

How do we handle such a thing in NestJS?

1

There are 1 answers

0
Vahid Najafi On BEST ANSWER

Finally I found the solution. The way is to use a custom strategy that extends the built-in transporter. Example::

import { ServerMqtt } from '@nestjs/microservices';
import { MqttClient } from '@nestjs/microservices/external/mqtt-client.interface';

class MyCustomStrategy extends ServerMqtt {
  bindEvents(mqttClient: MqttClient) {
    super.bindEvents(mqttClient);
    mqttClient.on('reconnect', () => console.log('Reconnecting...'));
  }
}

// and later
const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
  strategy: new MyCustomStrategy({
    url: 'mqtt://0.0.0.0:1883',
  }),
});