NestJS materials

Write an awesome doc for NestJS tips, tricks, notes, things which are not in the doc (or are but not really obvious) and experimented to figure them out and use them.

View on GitHub

RPC

A simple diagram showing how a NestJS app might be calling and RPC in a Python app

[!CAUTION]

This is still a network call. So do not call it like your codes who are living in the same codebase.

[!NOTE]

We can use any application level protocol for sending requests and receiving responses:

  • TCP: HTTP1, HTTP2.
  • UDP.
  • Websockets.
  • etc.

gRPC

NestJS

  1. Follow the official documentation opn how to bootstrap a NestJS app + gRPC.
    pnpx create-nx-workspace grpc --preset=nest --appName nestjs-client --bundler esbuild --packageManager pnpm --nxCloud skip
    
  2. I also love perfectionist for a good reason and that is the tidiness it gives you for little conf, so I highly recommend you take a look at it in their official doc.

    Or if you’re looking for something on how to get up to speed I guess this commit can be a real quick intro to how to use it. BTW I appreciate it if you give my repo a star in case it was helpful :slightly_smiling_face:.

    nx run-many -t lint --fix
    
  3. Write you’re protobuf file like what I did here at user.proto.
  4. Use the ts-proto to auto generate the interfaces and decorators for your gRPC controller.

    {
      "scripts": {
        "grpc:gen": "npx protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_opt=fileSuffix=.interface --ts_proto_opt=nestJs=true --ts_proto_opt=addNestjsRestParameter=true --ts_proto_out={projectRoot}/src/assets/interfaces -I {projectRoot}/src/assets/ {projectRoot}/src/assets/*.proto"
      }
    }
    

    For the complete solution look at this.

  5. Now just run the npm run grpc:gen or if you’re using Nx just run nx grpc:gen projectName.

  6. Congrats, you have your types and decorators. So let’s put them into use.

[!TIP]

For a complete example look at the nestjs-client.

Ref