Nestjstools Messaging Docs
  • Introduction
    • What is this library?
    • Supported message brokers
  • Getting Started
    • Installation
    • Initialize Module
    • Message Handler
    • Disaptch a message
  • Components
    • Message Handlers
    • Normalizers
    • Exception Listeners
    • Middlewares
    • Message Bus
    • Channel
  • Broker integration
    • RabbitMQ
    • Redis
    • Google PubSub
    • Amazon SQS
    • Nats
  • Best practice
    • CQRS based on RabbitMQ
    • Create wrapper class for Message Bus
    • Consumer as the background process
Powered by GitBook
On this page
  • 📦 Message Handlers
  • 🛠️ Defining a Message Handler
  • 🔁 Handling Multiple Routes
  • 🧠 Typed Message Input with @DenormalizeMessage()
  • 🧩 Registering Handlers
  • 📤 Triggering Handlers
  • Returning a Response
  • Summary
Export as PDF
  1. Components

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:

@MessageHandler('your.message', 'alternate.route')

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:

async handle(@DenormalizeMessage() message: SendMessage): Promise<void> {
  // Now message is an instance of SendMessage with all class logic available
}

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:

@Module({
  providers: [SendMessageHandler],
})
export class MessagingFeatureModule {}

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:

await messageBus.dispatch(
  new RoutingMessage(new SendMessage('Hello!'), 'your.message'),
);

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


Returning a Response

Handlers can return a MessageResponse if needed:

import { MessageResponse } from '@nestjstools/messaging';

return new MessageResponse({ result: 'OK' });

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

PreviousComponentsNextNormalizers

Last updated 9 days ago