Message Handler

πŸ’¬ Defining a Message & Message Handler

Messages are the core units of communication in your system. Each message can have a dedicated handler that processes it when received. This section explains how to define a message and implement a handler.


πŸ“¨ Define Your Message

A message is a simple class representing the data being sent between services or components:

// send-message.ts
export class SendMessage {
  constructor(
    public readonly content: string,
  ) {}
}

This message can now be published on a bus and handled by one or more consumers.


πŸ› οΈ Define a Message Handler

Handlers process incoming messages. They must implement the IMessageHandler<T> interface.

import { Injectable } from '@nestjs/common';
import { MessageHandler, IMessageHandler, MessageResponse } from '@nestjstools/messaging';
import { SendMessage } from './send-message';

@Injectable()
@MessageHandler('your.message') // This should match the message route you publish to
export class SendMessageHandler implements IMessageHandler<SendMessage> {
  async handle(message: SendMessage): Promise<MessageResponse | void> {
    console.log(message.content);
    // Add your business logic here
  }
}

πŸ” Multiple Routes

You can associate a single handler with multiple message routes:

@MessageHandler('your.message', 'your.message2')

🧠 Optional: Use @DenormalizeMessage() Decorator

If you want NestJS to automatically instantiate the incoming message as a proper class (rather than just receiving raw JSON), use the @DenormalizeMessage() decorator:

async handle(@DenormalizeMessage() message: SendMessage): Promise<MessageResponse | void> {
  // message is a real SendMessage instance
}

Last updated