Skip to content

MqttEvents

reference
1 min readUpdated

Kind: Type

Source: packages/microservices/events/mqtt.events.ts

Part of: Microservices

MQTT events map for the MQTT client. Key is the event name and value is the corresponding callback function.

MqttEvents defines the event-to-callback map used by the MQTT client integration. Each key represents an MQTT client event name, and its value is the handler invoked when that event is emitted. Use this type to keep MQTT lifecycle, message, and error handling centralized and consistently typed.

Definition

ts
{ connect: OnPacketCallback; reconnect: VoidCallback; disconnect: OnPacketCallback; close: VoidCallback; offline: VoidCallback; end: VoidCallback; error: OnErrorCallback; packetreceive: OnPacketCallback; packetsend: OnPacketCallback; }

Diagram

mermaid
graph LR
  Client[MQTT Client] -->|emits event| Events[MqttEvents map]
  Events --> Connect[connect handler]
  Events --> Message[message handler]
  Events --> Error[error handler]
  Events --> Close[close handler]

Usage

ts
import type { MqttEvents } from './mqtt.events';

const mqttEvents: MqttEvents = {
  connect: () => {
    console.log('Connected to MQTT broker');
  },

  message: (topic, payload) => {
    console.log(`Received message on ${topic}: ${payload.toString()}`);
  },

  error: (error) => {
    console.error('MQTT client error:', error);
  },

  close: () => {
    console.log('MQTT connection closed');
  },
};

// Register handlers with the MQTT client.
client.on('connect', mqttEvents.connect);
client.on('message', mqttEvents.message);
client.on('error', mqttEvents.error);
client.on('close', mqttEvents.close);

AI Coding Instructions

  • Keep event names aligned with the events emitted by the configured MQTT client library.
  • Define handlers in a MqttEvents object rather than scattering anonymous callbacks throughout connection setup code.
  • Handle error events explicitly to avoid unhandled MQTT client failures.
  • Treat message payloads as binary data and convert or parse them only after validating the topic and expected format.
  • Register the event map when creating the MQTT client so lifecycle handlers are attached before connection activity begins.

Was this page helpful?

Download as PDF
MqttEvents — NestJS head-to-head