|
| 1 | +import { Controller, Get, Post, Body, Query, HttpCode } from '@nestjs/common'; |
| 2 | +import { |
| 3 | + Client, |
| 4 | + MessagePattern, |
| 5 | + ClientProxy, |
| 6 | + Transport, |
| 7 | + ClientProxyFactory, |
| 8 | +} from '@nestjs/microservices'; |
| 9 | +import { Observable, of, from } from 'rxjs'; |
| 10 | +import { scan } from 'rxjs/operators'; |
| 11 | + |
| 12 | +@Controller() |
| 13 | +export class RMQController { |
| 14 | + client: ClientProxy; |
| 15 | + |
| 16 | + constructor() { |
| 17 | + this.client = ClientProxyFactory.create({ |
| 18 | + transport: Transport.RMQ, |
| 19 | + options: { |
| 20 | + urls: [`amqp://admin:admin@localhost`], |
| 21 | + queue: 'test', |
| 22 | + queueOptions: { durable: false }, |
| 23 | + }, |
| 24 | + }); |
| 25 | + } |
| 26 | + |
| 27 | + @Post() |
| 28 | + @HttpCode(200) |
| 29 | + call(@Query('command') cmd, @Body() data: number[]) { |
| 30 | + return this.client.send<number>({ cmd }, data); |
| 31 | + } |
| 32 | + |
| 33 | + @Post('stream') |
| 34 | + @HttpCode(200) |
| 35 | + stream(@Body() data: number[]): Observable<number> { |
| 36 | + return this.client |
| 37 | + .send<number>({ cmd: 'streaming' }, data) |
| 38 | + .pipe(scan((a, b) => a + b)); |
| 39 | + } |
| 40 | + |
| 41 | + @Post('concurrent') |
| 42 | + @HttpCode(200) |
| 43 | + concurrent(@Body() data: number[][]): Promise<boolean> { |
| 44 | + const send = async (tab: number[]) => { |
| 45 | + const expected = tab.reduce((a, b) => a + b); |
| 46 | + const result = await this.client |
| 47 | + .send<number>({ cmd: 'sum' }, tab) |
| 48 | + .toPromise(); |
| 49 | + |
| 50 | + return result === expected; |
| 51 | + }; |
| 52 | + return data |
| 53 | + .map(async tab => await send(tab)) |
| 54 | + .reduce(async (a, b) => (await a) && (await b)); |
| 55 | + } |
| 56 | + |
| 57 | + @MessagePattern({ cmd: 'sum' }) |
| 58 | + sum(data: number[]): number { |
| 59 | + return (data || []).reduce((a, b) => a + b); |
| 60 | + } |
| 61 | + |
| 62 | + @MessagePattern({ cmd: 'asyncSum' }) |
| 63 | + async asyncSum(data: number[]): Promise<number> { |
| 64 | + return (data || []).reduce((a, b) => a + b); |
| 65 | + } |
| 66 | + |
| 67 | + @MessagePattern({ cmd: 'streamSum' }) |
| 68 | + streamSum(data: number[]): Observable<number> { |
| 69 | + return of((data || []).reduce((a, b) => a + b)); |
| 70 | + } |
| 71 | + |
| 72 | + @MessagePattern({ cmd: 'streaming' }) |
| 73 | + streaming(data: number[]): Observable<number> { |
| 74 | + return from(data); |
| 75 | + } |
| 76 | +} |
0 commit comments