Message handlers define how your application reacts to specific messages dispatched on a bus. They encapsulate business logic triggered by inter-service or internal communication.
This page explains how to define, register, and work with message handlers using @nestjstools/messaging.
π οΈ Defining a Message Handler
A message handler is a class that implements the IMessageHandler<T> interface for a specific message type.
Example:
import { Injectable } from'@nestjs/common';import { MessageHandler, IMessageHandler, MessageResponse } from'@nestjstools/messaging';import { SendMessage } from'./send-message';@Injectable()@MessageHandler('your.message')exportclassSendMessageHandlerimplementsIMessageHandler<SendMessage> {asynchandle(message:SendMessage):Promise<MessageResponse|void> {console.log(message.content);// Your business logic here }}
π Handling Multiple Routes
You can bind the same handler to multiple routing keys:
This is useful if the same logic should run for different message sources.
π§ Typed Message Input with @DenormalizeMessage()
By default, the handler receives the raw message data (usually as a plain JavaScript object). If you want to receive it as a properly instantiated class, use the @DenormalizeMessage() decorator:
This is especially helpful when your message class contains methods, getters, or requires validation logic.
async handle(@DenormalizeMessage() message: SendMessage): Promise<void> {
// Now message is an instance of SendMessage with all class logic available
}
@Module({
providers: [SendMessageHandler],
})
export class MessagingFeatureModule {}
await messageBus.dispatch(
new RoutingMessage(new SendMessage('Hello!'), 'your.message'),
);
import { MessageResponse } from '@nestjstools/messaging';
return new MessageResponse({ result: 'OK' });