forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.controller.ts
More file actions
66 lines (57 loc) · 1.71 KB
/
Copy pathapp.controller.ts
File metadata and controls
66 lines (57 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { Controller, Get, Post, Body, Query, HttpCode } from '@nestjs/common';
import {
Client,
MessagePattern,
ClientProxy,
Transport,
ClientProxyFactory,
} from '@nestjs/microservices';
import { Observable, of, from } from 'rxjs';
import { scan, tap } from 'rxjs/operators';
@Controller()
export class AppController {
@Client({ transport: Transport.TCP })
client: ClientProxy;
@Post()
@HttpCode(200)
call(@Query('command') cmd, @Body() data: number[]): Observable<number> {
return this.client.send<number>({ cmd }, data);
}
@Post('stream')
@HttpCode(200)
stream(@Body() data: number[]): Observable<number> {
return this.client
.send<number>({ cmd: 'streaming' }, data)
.pipe(scan((a, b) => a + b));
}
@Post('concurrent')
@HttpCode(200)
concurrent(@Body() data: number[][]): Promise<boolean> {
const send = async (tab: number[]) => {
const expected = tab.reduce((a, b) => a + b);
const result = await this.client
.send<number>({ cmd: 'sum' }, tab)
.toPromise();
return result === expected;
};
return data
.map(async tab => await send(tab))
.reduce(async (a, b) => (await a) && (await b));
}
@MessagePattern({ cmd: 'sum' })
sum(data: number[]): number {
return (data || []).reduce((a, b) => a + b);
}
@MessagePattern({ cmd: 'asyncSum' })
async asyncSum(data: number[]): Promise<number> {
return (data || []).reduce((a, b) => a + b);
}
@MessagePattern({ cmd: 'streamSum' })
streamSum(data: number[]): Observable<number> {
return of((data || []).reduce((a, b) => a + b));
}
@MessagePattern({ cmd: 'streaming' })
streaming(data: number[]): Observable<number> {
return from(data);
}
}