All pages
Powered by GitBook
1 of 5

Getting Started

Installation

📦 Installation

To start using the @nestjstools/messaging library, you can install it using either npm or yarn, depending on your preference.

✅ Using npm

npm install @nestjstools/messaging

✅ Using yarn

yarn add @nestjstools/messaging

🧱 Requirements

  • Node.js v22 or higher

  • NestJS 10+

Initialize Module

🧩 Defining the Messaging Module

To use @nestjstools/messaging in your application, you need to register the MessagingModule in your root module (usually AppModule). This will make the messaging functionality available across all other modules in your app.

🔧 Starter Setup

import { Module } from '@nestjs/common';
import { MessagingModule, InMemoryChannelConfig } from '@nestjstools/messaging';


@Module({
  imports: [
    MessagingModule.forRoot({
      buses: [
        {
          name: 'my-channel.bus',
          channels: ['my-channel'],
        },
      ],
      channels: [
        new InMemoryChannelConfig({
          name: 'my-channel',
        }),
      ],
      debug: true,
    }),
  ],
})
export class AppModule {}

📌 Notes

  • MessagingModule.forRoot(...) registers the messaging system globally, meaning you don't need to import it in feature modules.

  • You must define at least one bus and one channel.

  • InMemoryChannelConfig our app will works on in-memory message transport layer.

  • Setting debug: true enables verbose logging to help with debugging message flow.

🚀 What’s Happening Here?

Property
Description

buses

Defines logical buses for message routing.

channels

Configures message channels (e.g., in-memory, Kafka, etc.).

debug

Enables or disables debug logging.

my-channel

A simple in-memory channel used by the message.bus.

⚠️ Important: Make sure this is defined in your AppModule or the main/root module to ensure messaging is globally available.

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
}

Disaptch a message

📤 Dispatching a Message

Messages can be dispatched from anywhere in your application—such as services, controllers, scheduled jobs, or event listeners. This allows for clean, decoupled communication between parts of your system.

🚀 Example: Dispatch from an HTTP Controller

Here’s a simple example of dispatching a message when an HTTP request is made:

import { Controller, Get } from '@nestjs/common';
import { MessageBus, IMessageBus, RoutingMessage } from '@nestjstools/messaging';
import { SendMessage } from './test/send-message';

@Controller()
export class AppController {
  // You can inject any bus you've defined in your MessagingModule config
  constructor(@MessageBus('message.bus') private readonly messageBus: IMessageBus) {}

  @Get()
  async dispatchMessage(): Promise<string> {
    // Dispatching a SendMessage instance to the route 'your.message'
    await this.messageBus.dispatch(
      new RoutingMessage(new SendMessage('Message from HTTP request'), 'your.message'),
    );

    return 'Message dispatched successfully!';
  }
}

📦 Components Explained

Component
Purpose

@MessageBus()

Injects a specific message bus by name.

RoutingMessage

Wraps the message and defines the route it should be sent to.

SendMessage

Your custom message class with data to transmit.

dispatch()

Sends the message to all subscribed handlers matching the route.


💡 Best Practices

  • Use meaningful routing keys (e.g., user.created, notification.send).

  • Define routing keys as the Enum

export enum EventMapper {
 UserCreated = 'my_app.event.user_created'
}
  • Always wrap domain objects in proper message classes instead of sending raw payloads.