Build a simple CRUD Server with gRPC and node.js

Tram Ho

gRPC is an RPC (remote procedure call) framework developed by Google, which has attracted a lot of attention from the software developer community over the years. In particular, gRPC is widely used in microservice systems because of many outstanding features such as: open source, independent of programming language, small binary size, HTTP / 2 support and cross-platform compatibility. . Google’s definition of gRPC is as follows:

gRPC is a language-neutral, platform-neutral remote procedure call (RPC) framework and toolset developed at Google. It lets you define a service using Protocol Buffers, a particularly powerful binary serialization toolset and language. It then lets you generate idiomatic client and server stubs from your service definition in a variety of languages.

In summary, the gRPC server will distribute the service methods. And the gRPC client on devices, on different platforms can call these service methods directly with the same parameters and return data types. gRPC uses Protocol Buffer to directly pass the data bytes for requests and response messages. Compared with RESTful APIs using JSON or XML, gRPC gives faster processing speed and smaller message size. The Protocol Buffer compiler will use the proto files to convert the bytes of data into corresponding data types per gRPC client. Because of this advantage will help reduce the conversion load on the server, the small message size is even more suitable for mobile applications.

In this article, we will build an extremely simple gRPC server with note.js. This server will provide simple services like create, read, update, delete for Pet object (CRUD). Then, we will also create a gRPC client using note.js to call the above service methods from the gRPC server we just created. Specifically:

  • Use npm and the necessary package dependencies to create the gRPC server.
  • Create proto file to define gRPC messages and services for Pet CRUD.
  • Create service method to get the list of pet.
  • Create a service method to create a new pet object.
  • Create a service method to delete a pet object.
  • Create gRPC client using note.js.

Create npm project, add dependencies

If your computer has not downloaded and installed note.js, follow the instructions at https://nodejs.org/en/download/

To get started, create a new directory called gRPC-Server , run the command npm init to init a npm project.

Then install 2 necessary dependencies using the command line:

  1. grpc: official gRPC dependency in note.js
  2. uuid: dependency is used to generate unique UUIDs based on timestamp.

Declare proto file

Next, create a new file named pets.proto with touch pets.proto command. This will be the file that we define Protocol Buffer Message and the gRPC services. The first thing to do in the proto file is to define the message Pet as the mapping of the Pet model object. Pet model will have the following 3 fields:

  1. String id
  2. String name
  3. String description

In addition, we also need to attach a number tag to each field, set syntax to version proto3 :

Implement and run gRPC server locally

After creating the proto file, we will implement the gRPC server using note.js. Create the file index.js containing the main entry points of the application. Inside this file, we import the grpc module, then use gRPC load to load the pets.proto file.

Next, we instantiate the gRPC server object and bind it to localhost on port 50051 and pass it to the Server Credential object for testing purposes.

Finally, there is the command start gRPC server.

Try running the server using the node index.js command. The command line will print out the corresponding message server running.

Create gRPC method to fetch list

The first method that we will implement will be the get list pet method. First, we need to declare Empty message and PetList message as follows:

The Empty message is a default empty sub for requests or responses that do not need to pass in / return any parameters (similar to Void in some programming languages). As for PetList message, we use keyword repeated to represent a data type of Pet array.

Next, we declare PetService and RPC method List. This method will take the input param of an Empty message and return the PetList message type. Then in the index.js file, initialize PetService by calling the addService function and pass two parameters: the PetService instance and the list param with the callback returned to the client list pet.

For simplicity of retrieval and testing, in this article, we will hard code an array of pet as above, inside the list handler method, this list pet returns.

Restart the server to deploy the list of pet service method just created.

Create gRPC client

To call the gRPC method and receive the response list pet, we need to create a gRPC note.js client. Create a new client.js file and import the gRPC module. Then xad file pets.proto and create a new client instance similar to initializing gRPC server above. The client will connect to localhost on port 50051. Finally, we need to export the client object we just created:

To call the list pet method using the gRPC client above, create a new file called get_pets.js . In this file, we import the client from the client.js file, then call the method list and pass an empty object to the first param. The second parameter will be the callback handler with the result returned with 2 variable error and response data. Here, we will check the error and print the corresponding result:

To test the gRPC client, run the gRPC server first, then run the node get_pets.js command, the output will be node get_pets.js on the command line as follows:

Create gRPC method to insert new object

The next method is used to insert a new object. This method will receive the request parameter of a Pet message and return the pet object you just inserted in the response.

In pets.proto file, declare new Insert method as follows:

In the index.js file, import the uuid/v1 module at the top of the file, which will be used to generate a unique uuid timstamp for the object inserted into the pet array. Inside the function handler, we retrieve the pet object from the request, then assign the new id to this object using the method uuidv1 . Then add this object to the pet array and return it in the callback with error = null.

To test the insert method above, create a new file insert_pet.js , create a new Pet object, import the client and call the insert method. Then print out the results.

Restart server, execute the command note insert_pet.js get the results:

Create gRPC method to delete an object

Similar to the insert method, we add a declaration for delete method in proto file. However, we need to declare more PetRequestId with a string id field, to be the input parameter for delete method.

Edit implement in index.js as follows:

Handle at gRPC client with delete_pet.js file:

Conclusion

Finally, we have completed and successfully deployed an extremely simple gRPC server. From there it is possible to distribute remote precedure calls to different multi-platform clients. In addition to the aforementioned capabilities, gRPC also supports a number of other features such as authentication, bidirectional steaming, flow control, binding, cancelling and timeout … So there is a lot to explore and explore gRPC.

Source article: https://www.alfianlosari.com/posts/building-grpc-server-note-crud-api-with-nodejs/

Final project: https://github.com/oNguyenXuanThanh/crud-grpc-notejs

Share the news now

Source : Viblo