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.
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 {}
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.
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.
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.
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.
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
}
}
@DenormalizeMessage()
DecoratorIf 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
}
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.
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!';
}
}
@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.
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.