Create wrapper class for Message Bus
🚀 Messaging Wrapper Module
This wrapper provides a reusable, centralized setup for working with the @nestjstools/messaging
library. It encapsulates sync-command bus into injectable services that can be easily used across your application.
📦 Purpose
Instead of configuring your message buses and channels in every module, this wrapper:
Exposes
SyncCommandBus
as injectable servicesEnsures clean separation of sync/async responsibilities
Keeps your controller/service code lean and focused
import { IMessageBus, RoutingMessage } from '@nestjstools/messaging';
/**
* A simplified interface for dispatching messages through a configured message bus.
* Encapsulates routing logic to keep controllers and services clean.
*/
export class InternalMessageBus {
constructor(private readonly messageBus: IMessageBus) {}
/**
* Dispatch a message using the given routing key.
*
* @param message The payload (command/event/etc.)
* @param routingKey The message routing key used by the bus
*/
async dispatch(message: object, routingKey: string): Promise<void> {
await this.messageBus.dispatch(new RoutingMessage(message, routingKey));
}
}
🧱 Module Setup
@Module({})
export class MessagingWrapperModule {
static forRoot(): DynamicModule {
return {
imports: [
MessagingModule.forRoot({
buses: [
{ name: 'sync-command.bus', channels: ['sync-channel'] },
],
channels: [
new InMemoryChannelConfig({
name: 'sync-channel',
}),
],
debug: true,
}),
],
providers: [
{
provide: 'MSyncCommandBus',
useFactory: (bus: IMessageBus) => new MessageBus(bus),
inject: ['sync-command.bus'],
},
],
exports: [
'MSyncCommandBus',
],
module: MessagingWrapperModule,
global: true,
};
}
}
🧩 Dependency Injection Tokens
These are helper tokens to inject the appropriate bus:
import { Inject } from '@nestjs/common';
import { Service } from '@messaging-wrapper/messaging-wrapper/dependency-injection/service';
export const SyncCommandBus = Inject('MSyncCommandBus');
🧪 Usage in a Controller
Example of dispatching a command using the injected @SyncCommandBus
:
@Controller('/orders')
export class OrderController {
constructor(@SyncCommandBus private readonly commandBus: MessageBus) {}
@Get('/simulate_complete')
simulateCompleteOrder(): string {
this.commandBus.dispatch(
new CompleteOrder('uuid-order-123', 'Star Wars: The New Galactic', 2),
'complete.order',
);
return 'ok';
}
}
Last updated