Skip to content

rodoufu/rest2grpc

Repository files navigation

rest2grpc

Current TravisCI build status. Current version. Current total lines. License.

Available at https://www.npmjs.com/package/rest2grpc

Example

Let's say we have a simple gRPC backend service that we want to expose as a REST endpoint, something like this protos file (Example.proto):

syntax = "proto3";

package example;

service Example {
	rpc SayHello (SayHelloRequest) returns (SayHelloResponse) {}
}

message SayHelloRequest {
	string name = 1;
}

message SayHelloResponse {
	string msg = 1;
}

We can use the following configuration (Example.yaml) to do so:

http:
  rules:
    - selector: example.Example.SayHello
      get: /sayHelloGet
      post: /sayHelloPost

That tells rest2grpc to create 2 endpoints:

  • /sayHelloGet answering to GET requests.
  • /sayHelloPost answering to POST requests.

Both requests are translated into gRPC and sent to the namespace example, service Example, and call the method SayHello.

Now to call everything you only need to:

import {Rest2gRPCServer} from 'rest2grpc';
(async () => {
	const address = 'localhost:50051';

	let configFile = `${__dirname}/Example.yaml`;
	const restServer = new Rest2gRPCServer(console);
	const protoPath = [`${__dirname}/protos`];
	const protoFile = "Example.proto";
	await restServer.register(configFile, protoPath, protoFile, address);

	restServer.start(3000);
})();

References