Skip to content

Commit 81eaca0

Browse files
committed
Controller for advanced GRPC tests added
1 parent 8f7aad1 commit 81eaca0

1 file changed

Lines changed: 97 additions & 0 deletions

File tree

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { Body, Controller, HttpCode, Post } from '@nestjs/common';
2+
import {
3+
Client, ClientGrpc, GrpcMethod,
4+
GrpcStreamMethod, GrpcStreamCall, Transport,
5+
} from '@nestjs/microservices';
6+
import { join } from 'path';
7+
import { Observable, of, Subject } from 'rxjs';
8+
9+
@Controller()
10+
export class AdvancedGrpcController {
11+
/*
12+
* HTTP Proxy Client defines loading pattern
13+
*/
14+
@Client({
15+
transport: Transport.GRPC,
16+
options: {
17+
package: 'proto_example.orders',
18+
protoPath: 'root.proto',
19+
loader: {
20+
includeDirs: [join(__dirname, './proto')],
21+
keepCase: true,
22+
},
23+
},
24+
})
25+
client: ClientGrpc;
26+
27+
/**
28+
* HTTP Proxy entry for support non-stream find method
29+
* @param id
30+
*/
31+
@Post()
32+
@HttpCode(200)
33+
call(@Body() id: number): Observable<number> {
34+
const svc = this.client.getService<any>('OrderService');
35+
return svc.find({ id });
36+
}
37+
38+
/**
39+
* GRPC stub for Find method
40+
* @param id
41+
*/
42+
@GrpcMethod('orders.OrderService')
43+
async find({ id }: { id: number }): Promise<any> {
44+
return of({
45+
id: 1,
46+
itemTypes: [1],
47+
shipmentType: {
48+
from: 'test',
49+
to: 'test1',
50+
carrier: 'test-carrier',
51+
},
52+
});
53+
}
54+
55+
/**
56+
* GRPC stub implementation for sync stream method
57+
* @param messages
58+
*/
59+
@GrpcStreamMethod('orders.OrderService')
60+
async sync(messages: Observable<any>): Promise<any> {
61+
const s = new Subject();
62+
const o = s.asObservable();
63+
messages.subscribe(msg => {
64+
s.next({
65+
id: 1,
66+
itemTypes: [1],
67+
shipmentType: {
68+
from: 'test',
69+
to: 'test1',
70+
carrier: 'test-carrier',
71+
},
72+
});
73+
}, err => {
74+
throw new Error(err.message);
75+
});
76+
return o;
77+
}
78+
79+
/**
80+
* GRPC stub implementation for syncCall stream method (implemented through call)
81+
* @param stream
82+
*/
83+
@GrpcStreamCall('orders.OrderService')
84+
async syncCall(stream: any) {
85+
stream.on('data', (msg: any) => {
86+
stream.write({
87+
id: 1,
88+
itemTypes: [1],
89+
shipmentType: {
90+
from: 'test',
91+
to: 'test1',
92+
carrier: 'test-carrier',
93+
},
94+
});
95+
});
96+
}
97+
}

0 commit comments

Comments
 (0)