KevinEdry / nestjs-trpc

Providing native support for decorators and implement an opinionated approach that aligns with NestJS conventions.
https://NestJS-tRPC.io
MIT License
65 stars 6 forks source link
api express nestjs trpc typescript

tRPC

Nestjs tRPC Adapter

An opinionated approach to building
End-to-end typesafe APIs with tRPC within NestJS.

weekly downloads MIT License Discord
Demo

The client above is not importing any code from the server, only its type declarations.

Introduction

NestJS tRPC is a library designed to integrate the capabilities of tRPC into the NestJS framework. It aims to provide native support for decorators and implement an opinionated approach that aligns with NestJS conventions.

Features

Quickstart

Installation

To install NestJS tRPC with your preferred package manager, you can use any of the following commands:

# npm
npm install nestjs-trpc zod @trpc/server

# pnpm
pnpm add nestjs-trpc zod @trpc/server

# yarn
yarn add nestjs-trpc zod @trpc/server

How to use

Here's a brief example demonstrating how to use the decorators available in NestJS tRPC:

// users.router.ts
import { Inject } from '@nestjs/common';
import { Router, Query, UseMiddlewares } from 'nestjs-trpc';
import { UserService } from './user.service';
import { ProtectedMiddleware } from './protected.middleware';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';

const userSchema = z.object({
  name: z.string(),
  password: z.string()
})

@Router()
class UserRouter {
  constructor(
    @Inject(UserService) private readonly userService: UserService
  ) {}

  @UseMiddlewares(ProtectedMiddleware)
  @Query({ output: z.array(userSchema) })
  async getUsers() {
    try {
      return this.userService.getUsers();
    } catch (error: unknown) {
      throw new TRPCError({
        code: "INTERNAL_SERVER_ERROR",
        message: "An error has occured when trying to get users.",
        cause: error
      })
    }
  }
}

šŸ‘‰ See full documentation on NestJS-tRPC.io. šŸ‘ˆ

All contributors

NestJS tRPC is developed by Kevin Edry, which taken a huge inspiration from both NestJS and tRPC inner workings.

A table of avatars from the project's contributors