Handling gRPC services with Nest.js

Felipe Marques
Webera
Published in
2 min readDec 16, 2021

--

In Nest.js, we have some transport layer implementations that are prepared for microservices. One of them is the gRPC transporter which is definitely one of the most interesting. In this article, we’ll explore the idea behind this layer and how we can implement it in NestJS.

Before getting your hands dirty and creating our microservice in NestJs, get comfortable if you want to know more about microservices by accessing the post below:

Creation of a project model

$ node -v
v10.14.1
$ yarn global add @nestjs/cli

Install the necessary packages

$ yarn add @nestjs/microservices @grpc/proto-loader grpc protobufjs

This time I created a project with Nestjs CLI and defined a module called module rest.

$ nest new nestjs-grpc-client
$ nest g mo rest

With let’s change the file main.ts

Let’s now create the .proto file’s job is to describe the service and the methods we want to use remotely.

A controller that provides RPC server functionality as a REST API

Antes de escrever nosso controller vamos configurar as opções que serão passada para o decorator @Client que será importado da biblioteca @nestjs/microservices.

In this example, we assume a use case where another gRPC server is called a web server built with Nest.js, and its function is provided as a REST API.

Next is the part that calls the function of the service that manages the Controller’s gRPC. The gRPC client is acquired by Decorator @Client the service actually used is acquired dynamically at the time of the lifecycle hook onModuleInit.

When I tried to get the service in Builder without using this lifecycle hook, an error occurred, so it seems better to use it silently.

In the real use situation, a pattern that responds after processing the information acquired from the gRPC server on the REST server-side is assumed.

In this case, I think it will be done in the service layer instead of dealing with the gRPC client directly in the controller like this time.

You can see that gRPC server content can be called a REST API as follows.

...{
"champion": {
"champion_id": 1,
"type": 1,
"name": "Felipe Marques",
"message": "uhuuuuu you are champion"
}
}
...

Conclusion

The Nest.js microservices package itself still looks underdeveloped (the interfaces are defined but not implemented), I welcome gRPC microservice development with Nest.js so I would like to continue using it in the future.

--

--