gRPC, which stands for "Google Remote Procedure Call," is an open-source framework developed by Google for enabling efficient and high-performance communication between distributed systems. It is used for building and connecting services, microservices, and applications across different programming languages and platforms.
Let's start our tutorial.
But before we start our lesson, I want to clarify that for the purposes of the lesson, I have tried to keep the code as simple as possible, without using unnecessary file structures or production-level code organization. The goal is merely to demonstrate the functionality of gRPC/tRPC in a simple and straightforward way so that it can be easily understood.
Today we will build a simple connection between a typescript client and server via gRPC/tRPC. But wait... what is a tRPC ? tRPC stands for Typescript Remote Procedure Call. Instead of producing an API definition for your backend with something like OpenAPI or GraphQL, tRPC directly infers and applies your TypeScript endpoints.
So our first step is to build our project folder, let's call it trpc-api. API is (Application Programming Interface) and REST API, GraphQL API, gRPC/tRPC API are all API's.
Our next step is to install some important dependancies inside our project /trpc-api:
yarn init -y
and our next command:
yarn add --dev @grpc/grpc-js @grpc/proto-loader typescript ts-node
@grpc/grpc-js is a JavaScript library for working with gRPC (Google Remote Procedure Call) in Node.js.
Some key features of @grpc/grpc-js include:
- Bi-directional streaming
- Protocol Buffers (ProtoBuf) support
- Promise-based API
- Interceptors
- Load balancing
Read more about @grpc/grpc-js@grpc/proto-loader is a Node.js module that provides functionality for loading Protocol Buffer (ProtoBuf) files and generating gRPC service client and server code dynamically.
Read more about @grpc/proto-loaderOur next step is to create these files and folders inside our project /trpc-api:
create server.ts
create client.ts
create proto folder and random.proto file
After this step is complete and our random.proto is ready, next step is:
yarn proto-loader-gen-types --grpcLib=@grpc/grpc-js
--outDir=proto/ proto/*.proto
To read more about this command, click hereThis command we execute in our Git Bash cli in our main directory /trpc-api. This is a command for generating TypeScript type definitions from Protocol Buffers (ProtoBuf) random.proto schema. After executing this command, we should see new files and folders in our proto folder:
/proto/random.ts
/proto/randomPackage/PingRequet.ts
/proto/randomPackage/PongResponse.ts
/proto/randomPackage/Random.ts
with all that.. we are pretty much done here and we can start coding our server.