> For the complete documentation index, see [llms.txt](https://docs.nestjstools.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nestjstools.com/best-practice/create-wrapper-class-for-message-bus.md).

# 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 services
* Ensures clean separation of sync/async responsibilities
* Keeps your controller/service code lean and focused

***

```typescript
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

```ts
@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:

```ts
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` :

```ts
@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';
  }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.nestjstools.com/best-practice/create-wrapper-class-for-message-bus.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
