by definition,
gRPC (gRPC Remote Procedure Calls) is an open source remote procedure call (RPC) system initially developed at Google. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as authentication, bidirectional streaming and flow control, blocking or nonblocking bindings, and cancellation and timeouts.
so many jargon words..right?. Let's break it down one by one.
gRPC built on top of Remote Procedure Call and Http/2 with Protocol Buffers.
what is Remote Procedure Call(RPC) ?
Firstly,Remote Procedure Call is a protocol where one program can use to request a service which is located in another program on different network without having to understand the network details.
it differs from normal procedure call. it makes use of kernel to make a request call to another service in the different network.
what is Protocol Buffer?
protocol buffers are language neutral way of serializing structure data. In simple terms, it converts the data into binary formats and transfer the data over the network. it is lightweight when compare to XML,JSON
How gRPC Works?
gRPC client sends the request to the server and gRPC server sends back the response. Most importantly, the way that gRPC sends and receive the request makes it more special
gRPC supports Bi-Directional streaming which is not supported in any other communication. Bi-Directional Streaming is sending stream of data and receiving stream of data. there are different way to send request/response
- Unary RPC's - it is a way of sending a single request and receiving the response
- Server Streaming RPC's : it is a process of sending the stream of data from server end.
- Client Streaming RPC's : it is a process of sending the stream of data from client side.
- Bi-Directional Streaming RPC's : it is a process of sending the stream of data from client as well as Server.
Implementing gRPC in Node.js
Let's see how we can use gRPC in Node.js by building a simple to-do application with CRUD APi's
Firstly, we need to install, dependencies for the application
npm install --save grpc
npm install --save uuid
After that, we need to create a file called todo.proto which is nothing but a protocol buffer of the data.
API to Fetch the Data
syntax = "proto3";
service TodoService {
rpc List(Empty) returns (TodoList) {}
}
message Empty {}
message Todo {
string id=1;
string title = 2;
bool iscompleted = 3;
}
message TodoList {
repeated Todo todo = 1;
}
Firstly, .proto file is something like a way we define to structure the request and response data.
Mainly, there are three parts in the proto buffer file which are Entity , Request Object and Response Object
message Empty {}
It is the Request Object which is used in the Service rpc
message TodoList {
repeated Todo todo = 1;
}
TodoList is the Response Object. which you sends to the client as the response. If you note that, there is something called repeated. it is something like an Array. Here, we are defining it like Array of todo
Now, you need to create a file called server.js where we handle the request
const grpc = require('grpc');
const uuid = require('uuid/v1');
const todoproto = grpc.load('todo.proto')
const server = new grpc.Server()
server.bind('127.0.0.1:50051',
grpc.ServerCredentials.createInsecure())
console.log('server is running at http://127.0.0.1:50051')
server.start()
if you run the server.js in the command line , it should display the message
server is running at http://127.0.0.1:50051
node server.js
Now, we need to Add the service to the server file. add the following code in server.js file
server.addService(todoproto.TodoService.service,{
list : (_,callback) =>{
callback(null,todos)
}
})
After that, create a file name called client.js which act as a client to sends request to gRPC Server.
const grpc = require('grpc');
const PROTO_PATH = './todo.proto'
const TodoService = grpc.load(PROTO_PATH).TodoService
const client = new TodoService('localhost:50051',
grpc.credentials.createInsecure())
module.exports = client
To make a call from client, you need to import the file in actual file which calls the service. create a file called get_todos.js which calls the service using client.
const client = require('./client')
client.list({},(error,todos) => {
if(!error){
console.log('successfully fetched todo lists');
console.log(todos);
}
else{
console.error(error);
}
});
To test the List API. you need to Run the server and client which calls the Service.
node server.js
node get_todos.js
Create Insert RPC Service to Create New Todo
Firstly, you need to add the insert service in the todo.proto .
syntax = "proto3";
service TodoService {
rpc List(Empty) returns (TodoList) {}
rpc Insert(Todo) returns (Todo) {}
}
message Empty {}
message Todo {
string id=1;
string title = 2;
bool iscompleted = 3;
}
message TodoList {
repeated Todo todo = 1;
}
After that, we need to add the insert service in server.js
server.addService(todoproto.TodoService.service,{
list : (_,callback) =>{
callback(null,todos)
},
insert : (call,callback) => {
let todo = call.request;
todo.id = uuid()
todos.push(todo)
callback(null,todo)
},
})
Now, you need to create a file called insert_todo.js which calls the insert service using the client.
const client = require('./client')
let newTodo = {
title : 'New checklist',
iscompleted : false
}
client.insert(newTodo,(error,todo) => {
if(!error){
console.log('New Todo inserted successfully');
}
else{
console.error(error);
}
})
After that, we can run the file using command line.
node server.js
node insert_todo.js
Similarly, we can define the Update and Delete Service calls and use it from the gRPC client
Complete Source Code can be found here : https://github.com/ganeshmani/grpc-node
Top comments (2)
you need this line in server.js or your call to get_todos will fail:
let todos = [];
yes. i have missed it to mention here. it will be available in the complete source code .. Thanks for mentioning it