NOTE: Development on grpc-bus is currently suspended as I have transitioned to Go from Node in all of my projects. If you want to adopt the project, let me know!
GRPC-bus is a mechanism to call GRPC services from the browser using a Node.JS server as a proxy. The link between the browser and Node.JS is defined by the user, but could be something like a WebSocket.
The server and client are expected to share the same / similar protobuf tree. For example, the same result should come from the following code on both the client and server:
builder.Build("mynamespace.MyType");
In this way the client can implement the ProtoBuf.JS RPC interfaces in the browser. Then, the grpc-bus package does the following:
Thus, we can call GRPC servers from the browser via a Node.JS websocket stream.
A full example can be found in the end-to-end tests under ./src/index.spec.ts
.
First, create your client, and give it a way to communicate with the server:
var protoTree = ProtobufJS.load('...');
var grpcBus = require('grpc-bus');
// MySendFunction takes a message object.
// This message should be passed to handleMessage on the server.
var client = new grpcBus.Client(protoTree, mySendFunction);
var tree = client.buildTree();
tree.MyService('localhost:3000').then(function(service) {
service.MyMethod({hello: 'world'}, function(err, resp) {
console.log(resp);
service.end();
});
});
You should always call service.end()
when you are done with a service handle, so the server knows it's safe to dispose it.
You'll notice that inside the then
block the API is exactly the same as the Node GRPC api.
A client must first be instantiated. The client object has to be given a function to send a message to the server, and should be called when the server sends a message to it. In this way, the user can implement their own transport, for example, websockets.
Next, the client can instantiate a service object, similar to the GRPC Node API. This returns a promise, resolved with a service handle with stubs for the methods on the service. The server will de-duplicate and re-use multiple service objects internally.
The client can then make calls against the remote service with the same API as the GRPC Node implementation.
When the client is done with a service object, it should dispose it. When all service objects are disposed, the server will disconnect from the service and forget the credentials used.