Message Bus

πŸ“¬ MessageBus

The MessageBus It is the core interface used to dispatch messages within your microservice architecture. It acts as the gateway between your application and the configured messaging channels, enabling seamless communication between services.

Whether you're calling from a controller, service, or any provider, the MessageBus gives you a powerful and type-safe way to route and send messages through your event-driven system.


πŸš€ What Is the MessageBus?

The MessageBus is injected via the @MessageBus('bus.name') decorator and gives you access to methods that allow you to:

  • Send messages to specific handlers via routing

  • Send raw or structured messages

  • Target a specific channel (e.g., in-memory, AMQP)

  • Trigger synchronous or asynchronous processing


πŸ›  Injecting the MessageBus

When configuring your messaging module, you define named buses. To use a bus, inject it using its name.

Example

import { Controller, Get } from '@nestjs/common';
import { MessageBus, IMessageBus, RoutingMessage } from '@nestjstools/messaging';
import { SendMessage } from './messages/send-message';

@Controller()
export class AppController {
  constructor(@MessageBus('message.bus') private readonly messageBus: IMessageBus) {}

  @Get()
  async dispatch(): Promise<string> {
    await this.messageBus.dispatch(
      new RoutingMessage(new SendMessage('Hello World!'), 'your.message'),
    );
    return 'Message dispatched!';
  }
}

🧩 RoutingMessage Structure

To route a message to the correct handler, use the RoutingMessage class:

new RoutingMessage(payload: object, route: string, messageOptions?: MessageOptions)

Example:

new RoutingMessage(
  new SendMessage('User created'),
  'user.created',
);

πŸ’‘ Bus-to-Channel Mapping

In your configuration, each bus can be connected to multiple channels:

MessagingModule.forRoot({
  buses: [
    {
      name: 'message.bus',
      channels: ['my-channel'], // All messages from this bus go here
    },
  ],
  channels: [
    new InMemoryChannelConfig({
      name: 'my-channel',
    }),
  ],
})

βœ… A message dispatched from a bus is passed to each of its configured channels.


πŸ”„ One Bus, Many Channels

Each bus can dispatch to multiple channels, and you can even configure different channels (e.g., RabbitMQ + InMemory) to receive the same message for hybrid systems.


πŸ” Benefits of MessageBus

Feature
Benefit

βœ… Type-safe

Dispatch class-based messages with strict typing

πŸ”Œ Pluggable

Supports multiple channels per bus

πŸ“‘ Scalable

Easily add more channels or handlers without changing your core logic

πŸ§ͺ Testable

Easily mock or simulate dispatches in testing environments

Last updated