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
  • 📤 Dispatching a Message
  • 🚀 Example: Dispatch from an HTTP Controller
  • 📦 Components Explained
  • 💡 Best Practices
Export as PDF
  1. Getting Started

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.

PreviousMessage HandlerNextComponents

Last updated 9 days ago