Message Handlers
📦 Message Handlers
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:
🔁 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()
@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.
🧩 Registering Handlers
Handlers are automatically discovered by NestJS as long as they are included in the providers of a module:
If you use a feature module, ensure that the module is imported by the root module and that MessagingModule
is globally available or also imported.
📤 Triggering Handlers
Handlers respond to messages dispatched through a message bus with a matching route:
If a handler is decorated with @MessageHandler('your.message')
, it will receive this message.
Returning a Response
Handlers can return a MessageResponse
if needed:
You can optionally implement response-handling logic in the calling component.
Summary
@MessageHandler()
Binds a handler to one or more routes
IMessageHandler<T>
Interface for handling a specific message type
@DenormalizeMessage()
Automatically deserializes message into class instance
MessageResponse
Optional way to return structured results from handlers, you can also return object
Last updated