mirror of
https://github.com/nestjs/nest.git
synced 2026-02-21 23:11:44 +00:00
Controller for advanced GRPC tests added
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
import { Body, Controller, HttpCode, Post } from '@nestjs/common';
|
||||
import {
|
||||
Client, ClientGrpc, GrpcMethod,
|
||||
GrpcStreamMethod, GrpcStreamCall, Transport,
|
||||
} from '@nestjs/microservices';
|
||||
import { join } from 'path';
|
||||
import { Observable, of, Subject } from 'rxjs';
|
||||
|
||||
@Controller()
|
||||
export class AdvancedGrpcController {
|
||||
/*
|
||||
* HTTP Proxy Client defines loading pattern
|
||||
*/
|
||||
@Client({
|
||||
transport: Transport.GRPC,
|
||||
options: {
|
||||
package: 'proto_example.orders',
|
||||
protoPath: 'root.proto',
|
||||
loader: {
|
||||
includeDirs: [join(__dirname, './proto')],
|
||||
keepCase: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
client: ClientGrpc;
|
||||
|
||||
/**
|
||||
* HTTP Proxy entry for support non-stream find method
|
||||
* @param id
|
||||
*/
|
||||
@Post()
|
||||
@HttpCode(200)
|
||||
call(@Body() id: number): Observable<number> {
|
||||
const svc = this.client.getService<any>('OrderService');
|
||||
return svc.find({ id });
|
||||
}
|
||||
|
||||
/**
|
||||
* GRPC stub for Find method
|
||||
* @param id
|
||||
*/
|
||||
@GrpcMethod('orders.OrderService')
|
||||
async find({ id }: { id: number }): Promise<any> {
|
||||
return of({
|
||||
id: 1,
|
||||
itemTypes: [1],
|
||||
shipmentType: {
|
||||
from: 'test',
|
||||
to: 'test1',
|
||||
carrier: 'test-carrier',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* GRPC stub implementation for sync stream method
|
||||
* @param messages
|
||||
*/
|
||||
@GrpcStreamMethod('orders.OrderService')
|
||||
async sync(messages: Observable<any>): Promise<any> {
|
||||
const s = new Subject();
|
||||
const o = s.asObservable();
|
||||
messages.subscribe(msg => {
|
||||
s.next({
|
||||
id: 1,
|
||||
itemTypes: [1],
|
||||
shipmentType: {
|
||||
from: 'test',
|
||||
to: 'test1',
|
||||
carrier: 'test-carrier',
|
||||
},
|
||||
});
|
||||
}, err => {
|
||||
throw new Error(err.message);
|
||||
});
|
||||
return o;
|
||||
}
|
||||
|
||||
/**
|
||||
* GRPC stub implementation for syncCall stream method (implemented through call)
|
||||
* @param stream
|
||||
*/
|
||||
@GrpcStreamCall('orders.OrderService')
|
||||
async syncCall(stream: any) {
|
||||
stream.on('data', (msg: any) => {
|
||||
stream.write({
|
||||
id: 1,
|
||||
itemTypes: [1],
|
||||
shipmentType: {
|
||||
from: 'test',
|
||||
to: 'test1',
|
||||
carrier: 'test-carrier',
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user