feat(microservices): add support for topic exchange (rabbitmq)

This commit is contained in:
Kamil Myśliwiec
2025-01-30 13:52:50 +01:00
parent 08fce4ac5f
commit 823fbab75d
6 changed files with 227 additions and 57 deletions

View File

@@ -0,0 +1,38 @@
import { INestApplication } from '@nestjs/common';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { RMQTopicExchangeController } from '../src/rmq/topic-exchange-rmq.controller';
describe('RabbitMQ transport (Topic Exchange)', () => {
let server: any;
let app: INestApplication;
beforeEach(async () => {
const module = await Test.createTestingModule({
controllers: [RMQTopicExchangeController],
}).compile();
app = module.createNestApplication();
server = app.getHttpAdapter().getInstance();
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.RMQ,
options: {
urls: [`amqp://0.0.0.0:5672`],
queue: 'test',
topicExchange: 'test',
},
});
await app.startAllMicroservices();
await app.init();
});
it(`should send message to wildcard topic exchange`, () => {
return request(server).get('/topic-exchange').expect(200, 'wildcard.a.b');
});
afterEach(async () => {
await app.close();
});
});

View File

@@ -0,0 +1,36 @@
import { Controller, Get } from '@nestjs/common';
import {
ClientProxy,
ClientProxyFactory,
Ctx,
MessagePattern,
RmqContext,
Transport,
} from '@nestjs/microservices';
import { lastValueFrom } from 'rxjs';
@Controller()
export class RMQTopicExchangeController {
client: ClientProxy;
constructor() {
this.client = ClientProxyFactory.create({
transport: Transport.RMQ,
options: {
urls: [`amqp://localhost:5672`],
queue: 'test',
topicExchange: 'test',
},
});
}
@Get('topic-exchange')
async topicExchange() {
return lastValueFrom(this.client.send<string>('wildcard.a.b', 1));
}
@MessagePattern('wildcard.*.*')
handleTopicExchange(@Ctx() ctx: RmqContext): string {
return ctx.getPattern();
}
}