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
π§ Optional: Use @DenormalizeMessage()
Decorator
@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
}
Last updated