For the complete documentation index, see llms.txt. This page is also available as Markdown.

Message Handlers

πŸ“¦ Message Handlers

Message handlers define how your application reacts to specific messages dispatched on a bus. They encapsulate business logic triggered by inter-service or internal communication.

This page explains how to define, register, and work with message handlers using @nestjstools/messaging.


πŸ› οΈ Defining a Message Handler

A message handler is a class that implements the IMessageHandler<T> interface for a specific message type.

Example:

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

@Injectable()
@MessageHandler('your.message')
export class SendMessageHandler implements IMessageHandler<SendMessage> {
  async handle(message: SendMessage): Promise<MessageResponse | void> {
    console.log(message.content);
    // Your business logic here
  }
}

πŸ” Handling Multiple Routes

You can bind the same handler to multiple routing keys:

This is useful if the same logic should run for different message sources.


🧠 Typed Message Input with @DenormalizeMessage()

By default, the handler receives the raw message data (usually as a plain JavaScript object). If you want to receive it as a properly instantiated class, use the @DenormalizeMessage() decorator:

This is especially helpful when your message class contains methods, getters, or requires validation logic.


🧩 Registering Handlers

Handlers are automatically discovered by NestJS as long as they are included in the providers of a module:

If you use a feature module, ensure that the module is imported by the root module and that MessagingModule is globally available or also imported.


πŸ“€ Triggering Handlers

Handlers respond to messages dispatched through a message bus with a matching route:

If a handler is decorated with @MessageHandler('your.message'), it will receive this message.


Returning a Response

Handlers can return a MessageResponse if needed:

You can optionally implement response-handling logic in the calling component.


Summary

Concept
Description

@MessageHandler()

Binds a handler to one or more routes

IMessageHandler<T>

Interface for handling a specific message type

@DenormalizeMessage()

Automatically deserializes message into class instance

MessageResponse

Optional way to return structured results from handlers, you can also return object


Note that handlers are visible across channels

Last updated

Was this helpful?