0.2.5 • Published 5 years ago

@dealercontrol/grpc-kit v0.2.5

Weekly downloads
8
License
MIT
Repository
github
Last release
5 years ago

grpc-kit

npm version

Use grpc more simply on Node.js.

quick start

install

$ npm install grpc @grpc/proto-loader grpc-kit

proto

syntax="proto3";

package greeter;

service Greeter {
  rpc Hello (RequestGreet) returns (ResponseGreet) {}
  rpc Goodbye (RequestGreet) returns (ResponseGreet) {}
}

message RequestGreet {
  string name = 1;
}

message ResponseGreet {
  string message = 1;
}

Server

const authService = require('./path/to/auth.service');
const {createServer} = require("grpc-kit");
const server = createServer();

server.use({
  protoPath: "/path/to/greeter.proto",
  packageName: "greeter",
  serviceName: "Greeter",
  routes: {
    hello: (call, callback) => {
      callback(null, { message: `Hello, ${call.request.name}` });
    },
    goodbye: async (call) => {
      return { message: `Goodbye, ${call.request.name}` };
    }
  },
  options: {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true
  },
  beforeCall: async function(call){
    // get metadata from call
    let { metadata } = call;

    // x-api-key is required
	if(typeof metadata['x-api-key'] === 'undefined'){
		throw new Error("Missing API Key");
	}
	let api_key = metadata['x-api-key'];
	// Authenticate the 
	let auth = await authService.authenticate(metadata['x-api-key']);
	
	if(!auth){
		throw new Error("Authentication Failed.");
	}

	return call.user_id = auth.user_id;
  },
  afterCall: function(call){
  // Maybe log the execution time of the call
  }
});
server.listen("0.0.0.0:50051");

Client

const {createClient} = require("grpc-kit");
const client = createClient({
  protoPath: "/path/to/greeter.proto",
  packageName: "greeter",
  serviceName: "Greeter",
  options: {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true
  }
}, "0.0.0.0:50051");

client.hello({ name: "Jack" }, (err, { message }) => {
  if(err) throw err;
  console.log(message);
});

client.goodbye({ name: "John" }, (err, { message }) => {
  if(err) throw err;
  console.log(message);
});

use stream

proto

syntax="proto3";

package stream_greeter;

service StreamGreeter {
  rpc ClientStreamHello(stream Message) returns(Message) {}
  rpc ServerStreamHello(Message) returns(stream Message) {}
  rpc MutualStreamHello (stream Message) returns (stream Message) {}
}

message Message {
  string message = 1;
}

Server

const {createServer} = require("grpc-kit");
const server = createServer();

server.use({
  protoPath: "/path/to/stream_greeter.proto"),
  packageName: "stream_greeter",
  serviceName: "StreamGreeter",
  routes: {
    clientStreamHello: (call, callback) => {
      call.on("data", (chunk) => {
        //exec when client wrote message
        console.log(chunk.message);
      });
      call.on("end", (chunk) => {
        callback(null, { message: "Hello! I'm fine, thank you!" })
      });
    },

    serverStreamHello: (call) => {
      console.log(call.request.message);
      call.write({ message: "Hello!" });
      call.write({ message: "I'm fine, thank you" });
      call.end();
    },

    mutualStreamHello: (call) => {
      call.on("data", (chunk) => {
        //exec when client wrote message
        console.log(chunk.message);
        if(chunk.message === "Hello!"){
          call.write({ message: "Hello!" });
        } else if(chunk.message === "How are you?"){
          call.write({ message: "I'm fine, thank you" });
        } else {
          call.write({ message: "pardon?" });
        }
      });
      call.on("end", (chunk) => {
        call.end();
      });
    }
  }
});

server.listen("0.0.0.0:50051");

Client

const {createClient} = require("grpc-kit");
const client = createClient({
  protoPath: "/path/to/stream_greeter.proto",
  packageName: "stream_greeter",
  serviceName: "StreamGreeter"
}, "0.0.0.0:50051");

client stream

const call = client.clientStreamHello((err, res) => {
  if(err) throw err;
  console.log(res.message);
});
call.write({ message: "Hello!" });
call.write({ message: "How are you?" });
call.end();

server stream

const call = client.serverStreamHello({ message: "Hello! How are you?" });
call.on("data", (chunk) => {
  console.log(chunk.message);
});
call.on("end", () => {
  //exec when server streaming ended.
});

mutual stream

const call = client.mutualStreamHello();
call.on("data", (chunk) => {
  console.log(chunk.message);
});
call.on("end", () => {
  //exec when server streaming ended.
});
call.write({ message: "Hello!" });
call.write({ message: "How are you?" });
call.end();

api

createServer(): GrpcServer

Create GrpcServer instance. GrpcServer is a wrapper class of grpc.Server providing simplified api to register services.

GrpcServer.use({protoPath,packageName,serviceName,options,routes}): GrpcServer

Register a service to provide from a server.

arg nametyperequired/optionaldescription
protoPathStringRequiredpath to .proto file
packageNameStringRequiredname of package
serviceNameStringRequiredname of service
options@grpc/proto-loader.OptionsOptionaloptions for @grpc/proto-loader to load .proto file. In detail, please check here out. Default is null
beforeCall(call) => void | PromiseOptionalevent hook to execute a function before a rpc is called. This is setup on a per-sevice basis
afterCall(call) => void | PromiseOptionalevent hook to execute a function after a rpc is called. This is setup on a per-sevice basis
routes{ [methodName]:(call, callback) => void | (call) => Promise }Requiredrouting map consists of a set of pair of method name and handler. Both of sync function and async function are available as a handler

GrpcServer.listen(address_port, credentials): GrpcServer

Start server. Alias to grpc.Server.bind() and grpc.Server.start().

arg nametyperequired/optionaldescription
address_portStringRequiredaddress and port of server to listen
credentialsgrpc.ServerCredentialsOptionalgrpc server credentials. Default to insecure credentials generated by grpc.ServerCredentials.createInsecure()

GrpcServer.close(force, callback): GrpcServer

Close server. Alias to grpc.Server.tryShutdown() and grpc.Server.forceShutdown.

arg nametyperequired/optionaldescription
forceBooleanOptionalflag if force shutdown or not. Default to false
callback()=>{}Optionalcall when shutdown completed. available only when force is false

createClient({protoPath,packageName,serviceName,options},address_port,credentials): grpc.Client

Create grpc.Client instance.

arg nametyperequired/optionaldescription
protoPathStringRequiredpath to .proto file
packageNameStringRequiredname of package
serviceNameStringRequiredname of service
options@grpc/proto-loader.OptionsOptionaloptions for @grpc/proto-loader to load .proto file. In detail, please check here out. Default is null
address_portStringRequiredaddress and port of server to listen
credentialsgrpc.ChannelCredentialsOptionalgrpc channel credentials. Default to insecure credentials generated by grpc.credentials.createInsecure()
0.2.6

5 years ago

0.2.5

5 years ago

0.2.4

5 years ago

0.2.3

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago