0
0
NestJSframework~5 mins

gRPC transport in NestJS

Choose your learning style9 modes available
Introduction

gRPC transport helps your NestJS app talk to other apps fast and clearly using a special language called Protocol Buffers.

You want your app to communicate quickly with other services.
You need a clear contract for messages between apps.
You want to build microservices that work well together.
You want to use streaming data between client and server.
You want to use a popular, efficient way to connect apps.
Syntax
NestJS
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';

@Controller()
export class MyGrpcService {
  @GrpcMethod('ServiceName', 'MethodName')
  methodName(data: RequestType): ResponseType {
    // handle request and return response
  }
}

@GrpcMethod decorator links your method to a gRPC service and method name.

Request and response types come from your Protocol Buffers definitions.

Examples
This example shows a simple gRPC method that returns a hero name by id.
NestJS
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';

@Controller()
export class HeroService {
  @GrpcMethod('HeroService', 'FindOne')
  findOne(data: { id: number }): { name: string } {
    return { name: 'Superman' };
  }
}
This example adds two numbers sent by the client and returns the result.
NestJS
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';

@Controller()
export class MathService {
  @GrpcMethod('MathService', 'Sum')
  sum(data: { a: number; b: number }): { result: number } {
    return { result: data.a + data.b };
  }
}
Sample Program

This NestJS gRPC service has one method called multiply. It takes two numbers and returns their product.

NestJS
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';

@Controller()
export class CalculatorService {
  @GrpcMethod('CalculatorService', 'Multiply')
  multiply(data: { x: number; y: number }): { product: number } {
    return { product: data.x * data.y };
  }
}
OutputSuccess
Important Notes

Make sure your .proto files match the service and method names exactly.

Use NestJS microservices options to configure gRPC transport in your main app module.

Test your gRPC methods with tools like BloomRPC or Evans for easy debugging.

Summary

gRPC transport lets NestJS apps talk fast and clearly using Protocol Buffers.

Use @GrpcMethod to connect your methods to gRPC service methods.

It is great for microservices and streaming data.