@madeweb/nestjs-service-bus
v1.0.0
Published
NestJS Azure Service Bus Microservice Transport
Downloads
37
Maintainers
Readme
Description
Azure Service Bus custom transport for NestJS microservices. Supports queues and topics/subscriptions with proper message routing via NestJS patterns.
Installation
$ npm i --save @azure/service-bus @madeweb/nestjs-service-busOptions
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| connectionString | string | — | Azure Service Bus connection string |
| queueName | string | — | Queue name (required when not using topics) |
| topicName | string | — | Topic name (required when not using queues) |
| subscriptionName | string | — | Subscription name (required with topics) |
| receiveMode | 'peekLock' \| 'receiveAndDelete' | 'peekLock' | Message receive mode |
| clientOptions | ServiceBusClientOptions | — | Azure SDK client options (retry, webSocket, userAgent) |
Client options (clientOptions)
Pass advanced options to the underlying ServiceBusClient:
interface ServiceBusClientOptions {
retryOptions?: RetryOptions;
webSocketOptions?: WebSocketOptions;
userAgentOptions?: UserAgentOptions;
}Usage
Microservice server (consumer)
// main.ts
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions } from '@nestjs/microservices';
import { AzureServiceBusStrategy } from '@madeweb/nestjs-service-bus';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
strategy: new AzureServiceBusStrategy({
connectionString: 'Endpoint=sb://<namespace>.servicebus.windows.net/;SharedAccessKeyName=<key>;SharedAccessKey=<key>',
queueName: 'my-queue',
}),
});
await app.listen();
}
bootstrap();Handling messages
The pattern sent by the client is stored in the message's applicationProperties and used to route to the correct handler:
import { Controller } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices';
@Controller()
export class MessageController {
@MessagePattern('order.created')
async handleOrderCreated(@Payload() data: any) {
console.log('Order created:', data);
}
@MessagePattern('order.cancelled')
async handleOrderCancelled(@Payload() data: any) {
console.log('Order cancelled:', data);
}
}Client (producer)
import { Injectable } from '@nestjs/common';
import { AzureServiceBusClient } from '@madeweb/nestjs-service-bus';
import { firstValueFrom } from 'rxjs';
@Injectable()
export class OrderService {
private readonly client: AzureServiceBusClient;
constructor() {
this.client = new AzureServiceBusClient({
connectionString: process.env.AZURE_SERVICE_BUS_CONNECTION!,
queueName: 'my-queue',
});
}
async createOrder(data: any) {
await this.client.connect();
return firstValueFrom(this.client.emit('order.created', data));
}
}Using Topics / Subscriptions
// Server
new AzureServiceBusStrategy({
connectionString: process.env.AZURE_SERVICE_BUS_CONNECTION!,
topicName: 'orders',
subscriptionName: 'service-a',
receiveMode: 'peekLock',
clientOptions: {
retryOptions: { maxRetries: 3 },
},
});
// Client
new AzureServiceBusClient({
connectionString: process.env.AZURE_SERVICE_BUS_CONNECTION!,
topicName: 'orders',
});Hybrid app (HTTP + microservice)
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.connectMicroservice({
strategy: new AzureServiceBusStrategy({
connectionString: process.env.AZURE_SERVICE_BUS_CONNECTION!,
queueName: process.env.AZURE_SERVICE_BUS_QUEUE!,
}),
});
await app.startAllMicroservices();
await app.listen(3000);
}Message routing
Messages are routed using the pattern field stored in the Azure Service Bus message applicationProperties. This allows a single queue/topic to handle multiple message patterns with different @MessagePattern() handlers — just like NestJS built-in transports (RabbitMQ, Redis, etc.).
Error handling
- PeekLock mode: messages are automatically completed on success and abandoned on error
- ReceiveAndDelete mode: messages are removed from the broker on delivery (no settlement required)
- Server errors are logged via NestJS
Loggerinstead ofconsole.error
Security and contributions
- Author - Luis Benavides
License
NestJS Azure Service Bus is MIT licensed.
