NestJS Enterprise Backend APIs · บทเรียน

การใช้งานและเรียกใช้เมธอด gRPC

เชื่อมต่อตัวจัดการ @GrpcMethod และพร็อกซี ClientGrpc สำหรับการเรียกคำขอและการตอบกลับแบบเอกเทศ

บทเรียน 2 จาก 413 ขั้นตอน

การใช้งานและเรียกใช้เมธอด gRPC เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Unary gRPC in NestJS

gRPC services in NestJS are defined by a .proto contract and implemented as ordinary providers decorated with gRPC handler metadata. The most common interaction is the unary call: the client sends a single request message and receives a single response message.

  • The server exposes handlers via @GrpcMethod (or @GrpcStreamMethod for streams).
  • The client obtains a typed proxy through ClientGrpc.getService() and calls methods that return Observables.

In this lesson we wire both ends of a unary request/response flow for an enterprise-style UsersService.

The .proto contract

Everything starts with the service contract. The package name and the service / rpc names are what NestJS uses to bind handlers and to resolve the client proxy.

  • package users maps to the transport option package: 'users'.
  • FindOne is the RPC NestJS will route to a matching handler.
syntax = "proto3";

package users;

service UsersService {
  rpc FindOne (UserById) returns (User) {}
}

message UserById {
  int32 id = 1;
}

message User {
  int32 id = 1;
  string name = 2;
  string email = 3;
}

Configuring the gRPC microservice

On the server, you start a microservice with the GRPC transport. The two critical options are package (must match the .proto package) and protoPath (where the contract lives).

  • url sets the bind address; default is localhost:5000.
  • You can pass an array of packages and proto paths for multi-service apps.
import { NestFactory } from '@nestjs/core';
import { Transport, MicroserviceOptions } from '@nestjs/microservices';
import { join } from 'path';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.createMicroservice<MicroserviceOptions>(
    AppModule,
    {
      transport: Transport.GRPC,
      options: {
        package: 'users',
        protoPath: join(__dirname, 'users.proto'),
        url: '0.0.0.0:5000',
      },
    },
  );
  await app.listen();
}
bootstrap();

Implementing a @GrpcMethod handler

A controller method becomes a unary RPC handler when you annotate it with @GrpcMethod. The decorator takes the service name and optionally the method name.

  • If you omit the method name, NestJS uses the PascalCase of the handler method name (so a method named findOne binds to FindOne).
  • The first argument is the deserialized request message; you simply return the response object (or a Promise/Observable of it).
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';

interface UserById { id: number; }
interface User { id: number; name: string; email: string; }

@Controller()
export class UsersController {
  private readonly users: User[] = [
    { id: 1, name: 'Ada', email: 'ada@corp.io' },
    { id: 2, name: 'Linus', email: 'linus@corp.io' },
  ];

  @GrpcMethod('UsersService', 'FindOne')
  findOne(data: UserById): User {
    return this.users.find((u) => u.id === data.id);
  }
}

Method name resolution rules

Binding depends entirely on naming. Get this wrong and the call fails at runtime with an UNIMPLEMENTED error.

  • Service name in @GrpcMethod('UsersService') must match the service in the .proto.
  • Method name: explicit second arg wins; otherwise the handler method name is capitalized to PascalCase.

For clarity in enterprise code, prefer passing both arguments explicitly so renames of the TypeScript method cannot silently break the wire contract.

Registering the client with ClientsModule

To consume a gRPC service, register a client in the consuming module. Each entry gets a name (an injection token) and the same transport options as the server.

  • package and protoPath point at the same contract the server uses.
  • url targets the server's bind address.
import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { join } from 'path';
import { ApiController } from './api.controller';

@Module({
  imports: [
    ClientsModule.register([
      {
        name: 'USERS_PACKAGE',
        transport: Transport.GRPC,
        options: {
          package: 'users',
          protoPath: join(__dirname, 'users.proto'),
          url: 'users-svc:5000',
        },
      },
    ]),
  ],
  controllers: [ApiController],
})
export class ApiModule {}

Getting the typed proxy with ClientGrpc

The injected client is a ClientGrpc instance, not the service itself. You must call getService() once the module is ready to obtain the strongly-typed proxy.

  • Resolve the proxy in onModuleInit so it exists before any request is handled.
  • The generic argument (UsersServiceClient) gives you full type safety on method calls.
import { Controller, Inject, OnModuleInit } from '@nestjs/common';
import { ClientGrpc } from '@nestjs/microservices';
import { Observable } from 'rxjs';

interface User { id: number; name: string; email: string; }
interface UsersServiceClient {
  findOne(data: { id: number }): Observable<User>;
}

@Controller('users')
export class ApiController implements OnModuleInit {
  private usersService: UsersServiceClient;

  constructor(@Inject('USERS_PACKAGE') private client: ClientGrpc) {}

  onModuleInit() {
    this.usersService = this.client.getService<UsersServiceClient>('UsersService');
  }
}

Calling a unary method returns an Observable

The proxy's methods are generated from the .proto and each returns an RxJS Observable, even for unary calls. NestJS can return the Observable directly from an HTTP handler, or you can convert it to a Promise.

  • Use firstValueFrom from RxJS when you need async/await ergonomics.
  • The proxy method name is the camelCase of the RPC (FindOne → findOne).
import { Controller, Get, Param, Inject, OnModuleInit } from '@nestjs/common';
import { ClientGrpc } from '@nestjs/microservices';
import { firstValueFrom, Observable } from 'rxjs';

interface User { id: number; name: string; email: string; }
interface UsersServiceClient {
  findOne(data: { id: number }): Observable<User>;
}

@Controller('users')
export class ApiController implements OnModuleInit {
  private usersService: UsersServiceClient;
  constructor(@Inject('USERS_PACKAGE') private client: ClientGrpc) {}

  onModuleInit() {
    this.usersService = this.client.getService<UsersServiceClient>('UsersService');
  }

  @Get(':id')
  async getUser(@Param('id') id: string): Promise<User> {
    return firstValueFrom(this.usersService.findOne({ id: Number(id) }));
  }
}

Why camelCase vs PascalCase matters

There are two distinct name transformations and mixing them up is a frequent bug source:

  • Server side: @GrpcMethod binds to the PascalCase RPC name (FindOne).
  • Client side: the proxy exposes the camelCase method (findOne) regardless of how the RPC is spelled in the proto.

So you call usersService.findOne(...) on the client even though the RPC and the server handler reference FindOne.

Mapping the Observable pipeline

Because unary calls return Observables, you can compose them with RxJS operators before exposing the result. This is idiomatic when you need to reshape or enrich the gRPC response.

  • This pure RxJS example mirrors the shape of a gRPC unary response without needing a running server, so it can execute standalone.
import { of, firstValueFrom } from 'rxjs';
import { map } from 'rxjs/operators';

interface User { id: number; name: string; email: string; }

// Simulates this.usersService.findOne({ id: 1 })
function findOne(data: { id: number }) {
  const row: User = { id: data.id, name: 'Ada', email: 'ada@corp.io' };
  return of(row);
}

async function main() {
  const dto = await firstValueFrom(
    findOne({ id: 1 }).pipe(
      map((u) => ({ userId: u.id, label: `${u.name} <${u.email}>` })),
    ),
  );
  console.log(JSON.stringify(dto));
}

main();

Handling errors with gRPC status codes

In enterprise services you should surface domain failures as proper gRPC statuses, not generic exceptions. Throw an RpcException with a numeric code from @grpc/grpc-js so callers can react deterministically.

  • status.NOT_FOUND (5) for a missing entity, status.INVALID_ARGUMENT (3) for bad input.
  • The client receives the status on the Observable's error channel.
import { Controller } from '@nestjs/common';
import { GrpcMethod, RpcException } from '@nestjs/microservices';
import { status } from '@grpc/grpc-js';

interface UserById { id: number; }
interface User { id: number; name: string; email: string; }

@Controller()
export class UsersController {
  private readonly users: User[] = [
    { id: 1, name: 'Ada', email: 'ada@corp.io' },
  ];

  @GrpcMethod('UsersService', 'FindOne')
  findOne(data: UserById): User {
    const found = this.users.find((u) => u.id === data.id);
    if (!found) {
      throw new RpcException({
        code: status.NOT_FOUND,
        message: `User ${data.id} not found`,
      });
    }
    return found;
  }
}

Quick Check

You implemented a server handler with @GrpcMethod('UsersService', 'FindOne'). On the consuming side you injected a ClientGrpc and called getService<UsersServiceClient>('UsersService'). Which method name do you invoke on the returned proxy to trigger this RPC?

Recap

You wired a complete unary gRPC flow in NestJS:

  • Defined the contract in a .proto with a package, service, and rpc.
  • Started a Transport.GRPC microservice and implemented the handler with @GrpcMethod('UsersService', 'FindOne'), returning the response object.
  • Registered a client via ClientsModule.register, resolved the typed proxy in onModuleInit with ClientGrpc.getService().
  • Called the camelCase proxy method, which returns an Observable — convertible with firstValueFrom.
  • Reported failures with RpcException and proper gRPC status codes.

Remember the naming split: server binds PascalCase, client calls camelCase.

เริ่มต้นได้ฟรี

เรียนรู้ TypeScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
20
บทเรียน
76

คำถามที่พบบ่อย

บทเรียน “การใช้งานและเรียกใช้เมธอด gRPC” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การใช้งานและเรียกใช้เมธอด gRPC” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การใช้งานและเรียกใช้เมธอด gRPC”

เชื่อมต่อตัวจัดการ @GrpcMethod และพร็อกซี ClientGrpc สำหรับการเรียกคำขอและการตอบกลับแบบเอกเทศ คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การใช้งานและเรียกใช้เมธอด gRPC” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม

ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การกำหนดบริการและข้อความใน Protobuf
  2. การใช้งานและเรียกใช้เมธอด gRPC
  3. RPC แบบสตรีมและการควบคุมแรงดันย้อนกลับ
  4. วิวัฒนาการของสัญญาและความเข้ากันได้ย้อนหลัง
← กลับไปที่ NestJS Enterprise Backend APIs