What is gRPC ? How to implement gRPC in Node.js

by definition,

1gRPC (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.

gRPC

Source : https://grpc.io/docs/guides/

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

1npm install --save grpc
2npm 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

1syntax = "proto3";
2
3
4service TodoService {
5 rpc List(Empty) returns (TodoList) {}
6}
7
8message Empty {}
9
10message Todo {
11 string id=1;
12 string title = 2;
13 bool iscompleted = 3;
14}
15
16message TodoList {
17 repeated Todo todo = 1;
18}

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

1message Empty {}

It is the Request Object which is used in the Service rpc

1message TodoList {
2 repeated Todo todo = 1;
3}

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

1const grpc = require("grpc")
2const uuid = require("uuid/v1")
3const todoproto = grpc.load("todo.proto")
4const server = new grpc.Server()
5
6server.bind("127.0.0.1:50051", grpc.ServerCredentials.createInsecure())
7console.log("server is running at http://127.0.0.1:50051")
8server.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

1node server.js

Now, we need to Add the service to the server file. add the following code in server.js file

1server.addService(todoproto.TodoService.service, {
2 list: (_, callback) => {
3 callback(null, todos)
4 },
5})

After that, create a file name called client.js which act as a client to sends request to gRPC Server.

1const grpc = require("grpc")
2
3const PROTO_PATH = "./todo.proto"
4
5const TodoService = grpc.load(PROTO_PATH).TodoService
6
7const client = new TodoService(
8 "localhost:50051",
9 grpc.credentials.createInsecure()
10)
11
12module.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.

1const client = require("./client")
2
3client.list({}, (error, todos) => {
4 if (!error) {
5 console.log("successfully fetched todo lists")
6 console.log(todos)
7 } else {
8 console.error(error)
9 }
10})

To test the List API. you need to Run the server and client which calls the Service.

1node server.js
2node get_todos.js

Create Insert RPC Service to Create New Todo

Firstly, you need to add the insert service in the todo.proto .

1syntax = "proto3";
2
3
4service TodoService {
5
6 rpc List(Empty) returns (TodoList) {}
7 rpc Insert(Todo) returns (Todo) {}
8}
9
10message Empty {}
11
12message Todo {
13 string id=1;
14 string title = 2;
15 bool iscompleted = 3;
16}
17
18message TodoList {
19 repeated Todo todo = 1;
20}

After that, we need to add the insert service in server.js

1server.addService(todoproto.TodoService.service, {
2 list: (_, callback) => {
3 callback(null, todos)
4 },
5 insert: (call, callback) => {
6 let todo = call.request
7 todo.id = uuid()
8 todos.push(todo)
9
10 callback(null, todo)
11 },
12})

Now, you need to create a file called insert_todo.js which calls the insert service using the client.

1const client = require("./client")
2
3let newTodo = {
4 title: "New checklist",
5 iscompleted: false,
6}
7
8client.insert(newTodo, (error, todo) => {
9 if (!error) {
10 console.log("New Todo inserted successfully")
11 } else {
12 console.error(error)
13 }
14})

After that, we can run the file using command line.

1node server.js
2node 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

To Read More

Kubernetes for Nodejs developers

Do you keep hearing the word kubernetes in the tech community and you couldn't u...

TypeScript Interfaces vs Types

In this article, we will see what are interfaces and types and the difference be...

How to find project ideas to practi...

Ever wondered what how to get a real world experience on web development while w...

Building a Production-grade Nodejs,...

This article is the first part of building a production grade nodejs,graphql and...

Modern React Redux Tutorials with R...

This tutorial explain how you can build an application using modern react redux ...

Building a Piano with React Hooks

In this article, we will see how to build a piano with react hooks. Building a P...

TypeScript Basics - The Definitive ...

In this article, we will learn some basics of typescript which helps you to deve...

Here's why podman is more secured t...

In this article we will see about podman and why it is more secured way to run c...

What is gRPC ? How to implement gRP...

Everyone talks about gRPC. Have you ever wonder how it works or how to implement...