API with NestJS #20. Communicating with microservices using the gRPC framework
source link: https://wanago.io/2020/11/30/api-nestjs-microservices-grpc-framework/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
With NestJS, we have quite a few transport layer implementations prepared for microservices. Among them, the gRPC transporter is definitely one of the most interesting. In this article, we explore the idea and implement it with NestJS.
gRPC is, at its core, a Remote Procedure Call (RPC) framework. Its main idea revolves around creating services in the form of functions that we can call remotely. It’s open-source and developed by Google. The gRPC framework is language-agnostic. Therefore, we can use it for communication across microservices using multiple programming languages.
The gRPC clients can directly call a method specified on a server. To describe the interface of the service and the payload messages, we use the protocol buffers. It is an efficient binary message format. It serializes very quickly and results in small messages.
Creating a .proto file
A first step to use gRPC is to create a .proto file using the protocol buffer language. This article uses the microservice that we’ve created in one of the previous parts of this series. Let’s break down the creation of the .proto step by step.
We’ll start by defining the version of the protocol buffers language. While there are some advantages and drawbacks to both, in this article, we use proto3.
We also want to use the package keyword with a name. We will later refer to it when setting up gRPC with NestJS.
The .proto file’s job is to describe the service and the methods we want to use remotely.
Even though we don’t need any parameters for the GetAllSubscribers method, we need to specify some message here – even if it is empty.
Assigning types and numbers to fields
Another important thing is to define our Subscriber.
Above, we use fundamental field types: integer and strings. There are various types that we can assign to fields. For a full list, visit the official documentation.
A more interesting topic is assigning field numbers. Every field in a massage needs a unique number. The gRPC framework uses the numbers to identify the fields in the message binary format.
Deep knowledge of the gRPC encoding is not needed to start working with the framework. Although, it is important to know that field numbers from 1 to 15 take just one byte to encode the field number and the type. If the field number is 16 and bigger, it takes two bytes. Therefore, we should keep the smaller number for parameters that frequently occur in our messages. We might even want to leave some room in the range of 1 through 15 to add new parameters here later.
Changing the name of the field does not affect the protocol buffer encoding. Changing the number assigned to property does break the compatibility between applications, so we need to watch out for that.
Dealing with arrays
The GetAllSubscribers method is supposed to return an array. Unfortunately, there is no straightforward way for our gRPC methods to return an array (other than a stream). Therefore, we create a GetAllSubscribers method that returns an object with the data property.
The repeated keyword means that this field can be repeated any number of times.
Using gRPC with NestJS
Aside from installing the @nestjs/microservices package, we also need the following:
Defining the microservice
For starters, let’s start with defining our microservice. Here, we need three things:
- the package’s name that we’ve defined in our .proto file,
- the path to the .proto file,
- the connection URL – defaults to localhost:5000.
It is worth mentioning that, by default, our build process does not copy the .proto files to the dist directory. Therefore, in my configuration, I point to the subscribers.proto in the src directory. Another approach would be to create a proto directory at the top of our project. We could also create a script that copies the .proto files to dist.
Running the above code initiates a gRPC server under the hood that can be accessed by the provided URL.
If we look under the hood, we can see that NestJS creates an instance of the grpc.Server class and begins handling requests. You can read more about it here.
In this article, we store the URL in our .env file:
With gRPC, we don’t use the @MessagePattern() decorator anymore. Instead, we mark our functions using the @GrpcMethod().
subscribers.service.tsPlease note that we don’t have the subscribers.controller.ts anymore. This time, we only have the SubscribersService that we mark with the @Controller() decorator. It works thanks to the fact that it matches the name of the service in the .proto file. We also add it to the controllers array in our SubscribersModule:
subscribers.module.tsThere are other ways to define a gRPC service with NestJS with additional arguments passed to the @GrpcMethod() decorator. If you want to know more, check out the documentation.
Creating a client
Once we have the microservice ready, we can connect to it from a client. The first thing to realize is that we need the same .proto for the client also. We also need the same environment variable that we’ve called GRPC_CONNECTION_URL.
subscribers.module.tsSince the SubscribersService is in another application, we need to create an interface to use it.
subscribers.service.interface.tsPlease note that we expect an empty object to be passed to the getAllSubscribers method because, with gRPC, we need to have some sorts of parameters. Even if they are empty.
Once we’ve registered our microservice, we can inject it into a controller. To use our remote service, we need to use the onModuleInit method that NestJS calls once it resolves all of its dependencies.
subscribers.controller.tsWith all of the above, we have a working connection with our microservice!
Summary
In this article, we’ve looked into the basics of establishing a gRPC connection with NestJS. This covered the fundamentals of the gRPC framework and Protocol Buffers language. We’ve also looked under to hood of NestJS to understand better what it does. Thanks to doing all of that, we learned about yet another transporter that we can use to communicate with our microservices.
Series Navigation<< API with NestJS #19. Using RabbitMQ to communicate with microservicesAPI with NestJS #21. An introduction to CQRS >>Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK