Basic Usage

Configuration

main.ts
import { createSbServer } from '@pebula/nesbus';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.connectMicroservice({ strategy: createSbServer() });
await app.startAllMicroservicesAsync();
await app.listen(3000);
}
bootstrap();

Client (emitting)

import { Injectable } from '@nestjs/common';
import { Sender } from '@azure/service-bus';
import { QueueEmitter, Topic } from '@pebula/nesbus';
@Injectable()
export class ServiceBusEmitClient {
@QueueEmitter({
name: 'nesbus-queue.demo'
})
myQueueEntity: Sender;
@Topic({
name: 'nesbus-topic.demo'
})
myTopicEntity: Sender;
}

After you add this to your module providers list you can import it anywhere in your app and start emitting to service bus.

Server (receiving)

import { Controller } from '@nestjs/common';
import { Queue, Subscription, Ctx, SbContext } from '@pebula/nesbus';
@Controller()
export class ServiceBusController {
@Queue<MethodDecorator>({
name: 'nesbus-queue.demo',
handlerOptions: {
autoComplete: false,
},
})
async myQueueEntity(@Ctx() context: SbContext) {
await context.getMessage().complete();
}
@Subscription<MethodDecorator>(({
name: 'nesbus-topic.demo'
})
async myTopicEntity(@Ctx() context: SbContext) {
}
}

Same way you define your REST routes... Bind a handler function to an incoming channel.

Using Reactive Handlers

import { Observable } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
import { Controller } from '@nestjs/common';
import { Queue, Subscription, SbContext } from '@pebula/nesbus';
@Controller()
export class ServiceBusController {
@Queue({
name: 'nesbus-queue.demo',
handlerOptions: {
autoComplete: false,
},
})
myQueueEntity = (source: Observable<SbContext>) => source
.pipe(
switchMap( async context => {
await context.getMessage().complete();
}),
)
@Subscription(({
name: 'nesbus-topic.demo'
})
myTopicEntity = (source: Observable<SbContext>) => source
.pipe(
tap( async context => {
}),
)
}

Using reactive handlers to chain the logic of your application.

This design allows using nesbus interceptors which act as plugins and can add a lot of functionality to your code with little effort.

tip

The reactive handler pattern works great with the @nestjs/cqrs module and in general most of the event driven designs out there. You can easily implement event sourcing with it.