# BusConfiguration

Creates a configuration in order to initialize a new [BusInstance](/reference/businstance.md).

## Methods

### withHandler(classHandler)

Registers a class handler that receives a message and performs a unit of work. When **Bus** is initialized it will configure the transport to subscribe to the type of message handled by the handler and upon receipt will forward the message through to the `handle()` function.

#### **Arguments**

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>classHandler</code></td><td>A class responsible for handling messages that implements <strong>Handler</strong></td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus } from '@node-ts/bus-core'
import { TestHandler } from './test-handler'

Bus.configure().withHandler(TestHandler)
```

See also [events](/guide/messages/events.md), [commands](/guide/messages/commands.md).

### withHandler(functionHandler)

Registers a function handler that receives a message and performs a unit of work. When **Bus** is initialized it will configure the transport to subscribe to the type of message handled by the function handler and upon receipt will forward the message to the function.

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>functionHandler</code></td><td>A functional handler mapping initialized using <code>handlerFor</code></td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus, handlerFor } from '@node-ts/bus-core'
import { TestEvent } from './test-event'

Bus.configure().withHandler(handlerFor(TestEvent, event => {}))
```

See also [events](/guide/messages/events.md), [commands](/guide/messages/commands.md).

### withCustomHandler(messageHandler,  customResolver)

Registers a custom handler that receives messages from external systems, or messages that don't implement the **Message** interface from **@node-ts/bus-messages**.

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>messageHandler</code></td><td>A handler that receives the custom message</td><td>None</td></tr><tr><td><code>customResolver</code></td><td>A discriminator that determines if an incoming message should be mapped to this handler</td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus } from '@node-ts/bus-core'
import { S3Event } from 'aws-sdk'

Bus.configure()
  .withCustomHandler(
    async (event: S3Event) => console.log('Received S3 event', { event }),
    {
      resolveWith: event => event.Records
        && event.Records.length
    }
  )   
```

See also [System messages](/guide/messages/system-messages.md).

### withWorkflow(workflow)

Registers a workflow definition so that all of the messages it depends on will be subscribed to and forwarded to the handlers inside the workflow.

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>workflow</code></td><td>Workflow definition to register</td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus } from '@node-ts/bus-core'
import { TestWorkflow } from './test-workflow'

Bus.configure().withWorkflow(TestWorkflow) 
```

See also [Workflows](/guide/workflows.md).

### withTransport(transport)

Configures **Bus** to use a different transport than the default **MemoryQueue.**

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>transport</code></td><td>A configured transport to use</td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus } from '@node-ts/bus-core'
import { SqsTransport, SqsTransportConfiguration } from '@node-ts/bus-sqs'

const sqsConfiguration: SqsTransportConfiguration = {
  // ...
}
const sqsTransport = new SqsTransport(sqsConfiguration)
Bus.configure().withTransport(sqsTransport) 
```

See also [Transports](/guide/transports.md).

### withLogger(loggerFactory)

Configures **Bus** to use a different logging provider than the default consoler logger.

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>loggerFactory</code></td><td>A factory that creates a new logger</td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus } from '@node-ts/bus-core'
import { CustomLogger } from './custom-logger'

Bus.configure().withLogger((target: string) => new CustomLogger(target))
```

See also [Loggers](/guide/loggers.md).

### withSerializer(serializer)

Configures **Bus** to use a different serialization provider. The provider is responsible for transforming messages to/from a serialized representation, as well as ensuring all object properties are a strong type.

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>serializer</code></td><td>Serializer to use</td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus } from '@node-ts/bus-core'
import { ClassSerializer } from '@node-ts/bus-class-serializer'

Bus.configure().withSerializer(new ClassSerializer())
```

See also [Serializer](/guide/serializers.md).

### withPersistence(persistence)

Configures **Bus** to use a different persistence provider than the default InMemoryPersistence provider. This is used to persist workflow data and is unused if not using workflows.

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>persistence</code></td><td>Persistence provider to use</td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus } from '@node-ts/bus-core'
import { PostgresPersistence, PostgresConfiguration } from '@node-ts/bus-postgres'

const postgresConfiguration: PostgresConfiguration = {
  connection: {
    connectionString: 'postgres://postgres:password@localhost:5432/postgres'
  },
  schemaName: 'workflows'
}
const postgresPersistence = new PostgresPersistence(postgresConfiguration)
Bus.configure().withPersistence(postgresPersistence)
```

See also [Persistence](/guide/persistence.md).

### withConcurrency(concurrency)

Sets the message handling concurrency beyond the default value of 1, which will increase the number of messages handled in parallel.concurrency

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>concurrency</code></td><td>The number of messages that can be handled in parallel</td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus } from '@node-ts/bus-core'

Bus.configure().withConcurrency(5)
```

### withContainer(containerAdapter)

```typescript
withContainer({
      get <T>(type: ClassConstructor<T>) {
        return container.get<T>(type)
      }
    })
```

Use a local dependency injection/IoC container to resolve handlers and workflows.

Configures **Bus** to use a different persistence provider than the default InMemoryPersistence provider. This is used to persist workflow data and is unused if not using workflows.

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>containerAdapter</code></td><td>An adapter that allows <strong>Bus</strong> to resolve class instances from the underlying IoC container</td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus } from '@node-ts/bus-core'
import { Container } from 'inversify'

const container = new Container()
Bus.configure().withContainer({
      get <T>(type: ClassConstructor<T>) {
        return container.get<T>(type)
      }
})   
```

See also [Dependency injection.](/guide/dependency-injection.md)

### withMessageReadMiddleware(middleware)

```typescript
  withMessageReadMiddleware<TransportMessageType = unknown> (
    messageReadMiddleware: Middleware<TransportMessage<TransportMessageType>>
  )
```

Run custom middleware before/after the point a message is read from the transport and then dispatched to handlers and workflow handlers.

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>middleware</code></td><td>A middleware function that will be executed after a message is read from the transport and before it is dispatched to handlers.</td><td>None</td></tr></tbody></table>

#### Example

```typescript
import { Bus, Middleware, Next, TransportMessage } from '@node-ts/bus-core'

const messageTimingMiddleware = async (
  context: TransportMessage<unknown>,
  next: Next
) => {
  const start = Date.now()
  await next()
  const end = Date.now()
  const durationMs = end - start
  console.log(
    'Message handled',
    { messageName: context.domainMessage.$name, durationMs }
  )
}
const bus = await Bus.configure()
  .withMessageReadMiddleware(messageTimingMiddleware)
```

See also [Middleware](/guide/middleware.md).

### withRetryStrategy(retryStrategy)

```typescript
  withRetryStrategy({
    calculateRetryDelay (currentAttempt: number): number
  })
```

Configure the bus to use a different retry strategy instead of the default.

#### Arguments

<table><thead><tr><th width="220.36412604232706">Argument</th><th width="342.81368434354914">Description</th><th width="150">Default</th></tr></thead><tbody><tr><td><code>retryStrategy</code></td><td>An implementation of <code>RetryStrategy</code> that calculates the delay between retrying failed messages.</td><td><code>DefaultRetryStrategy</code></td></tr></tbody></table>

#### Example

```typescript
const bus = await Bus.configure()
  .withRetryStrategy({
    calculateRetryDelay (currentAttempt: number) { return Math.pow(2, currentAttempt) }
  }) 
  .initialize()
```

See also [Retry Strategies](/guide/retry-strategies.md).

### initialize(\[options])

Initialize a configured **BusInstance**. This should be called after all options have been provided for the configuration.


---

# Agent Instructions: 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:

```
GET https://bus.node-ts.com/reference/busconfiguration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
