In this blog, we are going to connect with grpc server using node.js (express). As per the official document, grpc is:
gRPC is a modern open source high performance RPC framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services
To learn more about grpc, please follow the official document.
So let’s get started.
Connect GRPC Server Using Node.js (Express)
To create a grpc server we need to have a proto file where the services and messages are defined. For simplicity, let’s create notes.proto file having the following content.
syntax = "proto3";
package testnoteservice;
service NoteService {
rpc List (Empty) returns (NoteList) {}
}
message Empty {}
message Note {
string id = 1;
string title = 2;
string content = 3;
}
message NoteList {
repeated Note notes = 1;
}
Your package.json for the grpc server/client needs to have similar content:
{
"name": "grpc-study",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": ""
},
"author": "",
"license": "ISC",
"dependencies": {
"grpc": "^1.20.3",
"uuid": "^3.3.2"
}
}
Now, let’s create the index.js file on the root folder and paste the given code from below.
const grpc = require('grpc')
const notesProto = grpc.load('notes.proto')
const notes = [
{id:'1',title:'Note 1', content:'content 1'},
{id:'2',title:'Note 2',content:'content 2'}
]
const server = new grpc.Server()
server.addService(notesProto.testnoteservice.NoteService.service,{
list:(call,callback) => {
callback(null,notes)
}
})
server.bind('127.0.0.1:50051', grpc.ServerCredentials.createInsecure())
server.start()
if(server.started){
console.log('Server running at http://127.0.0.1:50051')
}
If you run node index.js, you should have your grpc server started and ready to accept connections. So, let’s build a client for our server. For that create client.js on the same folder. Here is the content for the client.js
const grpc = require('grpc')
const PROTO_PATH = __dirname +'/notes.proto'
const NoteService = grpc.load(PROTO_PATH).testnoteservice.NoteService
const client = new NoteService('127.0.0.1:50051',
grpc.credentials.createInsecure())
module.exports = client
To this point, we have both grpc client and server up and running. Its time for now to create an express server whose primary functionality would be to accept the HTTP request and processing to grpc server.
Create api_server folder and init with the following package.json file.
{
"name": "api_server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.0",
"grpc-express": "^1.0.1-beta",
"path": "^0.12.7",
"protobufjs": "^6.8.8"
}
Now, create the index.js file having the following content
var grpcExpress = require('grpc-express');
var express = require('express');
const path = require('path');
var ProtoBuf = require('protobufjs')
var app = express();
const noteClient = require('../client');
grpc = require('grpc'),
app.get('/list',(req,res,next) => {
noteClient.list({}, meta,(error, notes) => {
if (!error) {
//res.send(notes) for json response else >>
ProtoBuf.load('../notes.proto', function(err,root){
if (err)
throw err;
var NoteList = root.lookupType("testnoteservice.NoteList");
var errMsg = NoteList.verify(notes);
if (errMsg)
throw Error(errMsg);
var notelist = NoteList.create(notes);
res.send(NoteList.encode(notelist).finish()) //for buffer response
})
} else {
console.error(error)
}
})
})
const port = 7070
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Start both api server and grpc server, then navigate to the URL http://localhost:7070/list which now will return the notes list from grpc server.
We successfully connected grpc server using node.js (express)