This document covers basic fundamentals of using grpc classes that is generated by protoc-gen-ts.
There are not too many ways to go when it comes to using grpc with node. There are two official server implementation of grpc for node out there. Both of them are maintained by google.
this plugin generates abstract classes and rpc definitions can be consumed by these packages. all you have to do is
just write your business logic and rest will be taken care of. When you have a rpc called Storage
, protoc-gen-ts
will
generate two classes; UnimplementedStorageService
and StorageClient
.
UnimplementedStorageService
is an abstract class
that has methods which consists of your rpc methods and an additional field called definition
.
for each method, you will get an abstract method whose signature is 1-1 match of your rpc method.
definition
field will have the definiton of your service which later can be passed to grpc to allocate
the appropriate endpoints for your rpc methods.
StorageClient
will be your client to interact with this service. It consists of methods which accepts the right type of messages
to interact with the server.
Enough talking; lets implement a server that would work without any hussle.
For the sake of keeping things simple, we will create a storage service that has only one unary rpc method.
given the proto storage.proto
syntax="proto3";
message Query {
string id = 1;
}
message Object {
string name = 1;
}
service Storage {
rpc get(Query) returns (Object);
}
you would write something for the server that looks like below
(assuming the proto output and server.ts
is in the same directory)
import * as grpc from "@grpc/grpc-js";
import { Query, UnimplementedStorageService, Object } from "./storage";
class Storage extends UnimplementedStorageService {
get(call: grpc.ServerUnaryCall<Query, Object>, callback: grpc.requestCallback<Object>): void {
console.log(call.request.id);
callback(null, new Object({ id: call.request.id }));
}
}
const server = new grpc.Server();
server.addService(UnimplementedStorageService.definition, new Storage());
server.bindAsync(
"0.0.0.0:4884",
grpc.ServerCredentials.createInsecure(),
() => server.start()
);
to interact with this service you will need to use StorageClient
as follows.
import {StorageClient, Query} from "./storage";
const storage = new StorageClient("0.0.0.0:4884", grpc.credentials.createInsecure());
storage.get(new Query(), (object) => console.log(object));
// also available as promise if the experimental promises enabled.
const object = await storage.get(new Query());