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.
Last updated