1 | initial version |
To incorporate a ServerWritableStream in nest.js using gRPC, follow these steps:
service MyService {
rpc MyMethod(stream MyRequest) returns (MyResponse) {}
}
message MyRequest {
string id = 1;
string content = 2;
}
message MyResponse {
bool success = 1;
}
grpc_tools_node_protoc --plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts --ts_out=./src --grpc_out=./src --proto_path=./proto ./proto/my_service.proto
@Injectable()
export class MyService implements grpcService<MyService> {
async myMethod(stream: ServerWritableStream<MyRequest, MyResponse>) {
// Handle incoming requests from the client
stream.on('data', (data: MyRequest) => {
console.log('Received request:', data);
});
// Send response back to the client
await stream.write({ success: true });
// Close the stream
stream.end();
}
}
async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.GRPC,
options: {
package: 'my_package',
protoPath: join(__dirname, './proto/my_service.proto'),
},
});
await app.listenAsync();
}
const client = new MyServiceClient('localhost:5000', credentials.createInsecure());
const stream = client.myMethod((error, response) => {
console.log('Stream closed');
});
// Send multiple requests to the server and handle the responses
stream.write({ id: '1', content: 'Hello' });
stream.write({ id: '2', content: 'World' });
stream.on('data', (data: MyResponse) => {
console.log('Received response:', data);
});
stream.on('end', () => {
console.log('Stream ended');
});