72

API with NestJS #20. Communicating with microservices using the gRPC framework

 3 years ago
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.
API with NestJS #20. Communicating with microservices using the gRPC framework

JavaScript NestJS TypeScript

November 30, 2020
This entry is part 20 of 21 in the API with NestJS

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.

syntax = "proto3";

We also want to use the package keyword with a name. We will later refer to it when setting up gRPC with NestJS.

package subscribers;

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

service SubscribersService {
  rpc GetAllSubscribers (GetAllSubscribersParams) returns (SubscribersResponse) {}
  rpc AddSubscriber (CreateSubscriberDto) returns (Subscriber) {}

Even though we don’t need any parameters for the GetAllSubscribers method, we need to specify some message here – even if it is empty.

message GetAllSubscribersParams {}

Assigning types and numbers to fields

Another important thing is to define our Subscriber.

message Subscriber {
  int32 id = 1;
  string email = 2;
  string name = 3;
message CreateSubscriberDto {
  string email = 1;
  string name = 2;

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.

message SubscribersResponse {
  repeated Subscriber data = 1;

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:

npm install grpc @grpc/proto-loader

Defining the microservice

For starters, let’s start with defining our microservice. Here, we need three things:

  1. the package’s name that we’ve defined in our .proto file,
  2. the path to the .proto file,
  3. the connection URL – defaults to localhost:5000.
main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { join } from 'path';
import { ConfigService } from '@nestjs/config';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService = app.get(ConfigService);
  await app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.GRPC,
    options: {
      package: 'subscribers',
      protoPath: join(process.cwd(), 'src/subscribers/subscribers.proto'),
      url: configService.get('GRPC_CONNECTION_URL')
  app.startAllMicroservices();
bootstrap();

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:

GRPC_CONNECTION_URL=localhost:5000

With gRPC, we don’t use the @MessagePattern() decorator anymore. Instead, we mark our functions using the @GrpcMethod().

subscribers.service.ts
import { Controller } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import Subscriber from './subscriber.entity';
import CreateSubscriberDto from './dto/createSubscriber.dto';
import { Repository } from 'typeorm';
import { GrpcMethod } from '@nestjs/microservices';
@Controller()
export class SubscribersService {
  constructor(
    @InjectRepository(Subscriber)
    private subscribersRepository: Repository<Subscriber>,
  @GrpcMethod()
  async addSubscriber(subscriber: CreateSubscriberDto) {
    const newSubscriber = await this.subscribersRepository.create(subscriber);
    await this.subscribersRepository.save(newSubscriber);
    return newSubscriber;
  @GrpcMethod()
  async getAllSubscribers() {
    const data = await this.subscribersRepository.find();
    return {

Please 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.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import Subscriber from './subscriber.entity';
import { SubscribersService } from './subscribers.service';
@Module({
  imports: [TypeOrmModule.forFeature([Subscriber])],
  exports: [],
  controllers: [SubscribersService],
export class SubscribersModule {}

There 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.ts
import { Module } from '@nestjs/common';
import SubscribersController from './subscribers.controller';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ClientProxyFactory, Transport } from '@nestjs/microservices';
import { join } from "path";
@Module({
  imports: [ConfigModule],
  controllers: [SubscribersController],
  providers: [
      provide: 'SUBSCRIBERS_PACKAGE',
      useFactory: (configService: ConfigService) => {
        return ClientProxyFactory.create({
          transport: Transport.GRPC,
          options: {
            package: 'subscribers',
            protoPath: join(process.cwd(), 'src/subscribers/subscribers.proto'),
            url: configService.get('GRPC_CONNECTION_URL')
      inject: [ConfigService],
export class SubscribersModule {}

Since the SubscribersService is in another application, we need to create an interface to use it.

subscribers.service.interface.ts
import CreateSubscriberDto from './dto/createSubscriber.dto';
import Subscriber from './subscriber.service';
interface SubscribersService {
  addSubscriber(subscriber: CreateSubscriberDto): Promise<Subscriber>
  getAllSubscribers(params: {}): Promise<{data: Subscriber[]}>
export default SubscribersService;

Please 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.ts
import {
  Body,
  Controller,
  Post,
  UseGuards,
  UseInterceptors,
  ClassSerializerInterceptor, Inject, OnModuleInit,
} from '@nestjs/common';
import JwtAuthenticationGuard from '../authentication/jwt-authentication.guard';
import CreateSubscriberDto from './dto/createSubscriber.dto';
import { ClientGrpc } from '@nestjs/microservices';
import SubscribersService from './subscribers.service.interface';
@Controller('subscribers')
@UseInterceptors(ClassSerializerInterceptor)
export default class SubscribersController implements OnModuleInit {
  private subscribersService: SubscribersService;
  constructor(@Inject('SUBSCRIBERS_PACKAGE') private client: ClientGrpc) {}
  onModuleInit() {
    this.subscribersService = this.client.getService<SubscribersService>('SubscribersService');
  @Get()
  async getSubscribers() {
    return this.subscribersService.getAllSubscribers({});
  @Post()
  @UseGuards(JwtAuthenticationGuard)
  async createPost(@Body() subscriber: CreateSubscriberDto) {
    return this.subscribersService.addSubscriber(subscriber);

With 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 >>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK