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
  • 💬 Defining a Message & Message Handler
  • 📨 Define Your Message
  • 🛠️ Define a Message Handler
  • 🔁 Multiple Routes
  • 🧠 Optional: Use @DenormalizeMessage() Decorator
Export as PDF
  1. Getting Started

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
}

PreviousInitialize ModuleNextDisaptch a message

Last updated 9 days ago