Giter Site home page Giter Site logo

trpc-selections's Introduction

tRPC Selections

GraphQL-like selections in pure TypeScript w/ tRPC.

Comparison with GraphQL

GraphQL requires additional tooling and complex workflows to integrate nicely with TypeScript:

/**
  The following example is from Apollo Client's documentation.
  @see https://www.apollographql.com/docs/react/get-started/
*/
const result = await client.query({
  // Since GraphQL uses a custom query language,
  // TypeScript can't verify that this following GraphQL
  // query is valid and the developer needs to install
  // additional tooling for better DX.
  query: gql`
    query GetLocations {
      locations {
        id
        name
        description
        photo
      }
    }
  `,
});

// Code generation scripts are required for TypeScript
// to correctly infer the type of `result`
console.log(result);

In contrast, tRPC Selections leverages tRPC's end-to-end type safety to integrate well with TypeScript out-of-the-box without any code generation scripts:

const result = await withSelection(
  (selection) => trpc.locations.get.query({ selection }),
  // TypeScript checks the selection fields based on the `Location` model
  // (which is inferred by the return value of `trpc.locations.get`)
  {
    id: true,
    name: true,
    description: true,
    photo: true
  }
)

// The type of `result` is correctly inferred using the
// fields passed in the above selections object
console.log(result);

Motivation

Oftentimes, we need to query the backend for a specific subset of fields for a certain model. While GraphQL is a great solution for this, it adds a significant amount of overhead from complex operation resolution algorithms and the use of custom query and schema language that forces developers to resort to code generation scripts in order to integrate well with TypeScript.

Instead, trpc-selections adds on top of tRPC's native type-safety (i.e. no code generation) by introducing the concept of a "selection object" that can be passed to the backend to select a specific subset of fields. It works out-of-the-box with TypeScript without the need for code generation.

Usage

With Prisma

TODO

// server/router.ts
import { z } from 'zod';
import { zSelection } from 'trpc-selection'
import { select } from 'typegeese'

import { procedure, router } from '~/utils/trpc.ts'
import { UserModel } from '~/utils/db.ts'

export const appRouter = router({
  getUser: procedure
    .input(
      z.object({
        id: z.string(),
        selection: zSelection()
      })
    )
    .query(async ({ input }) => {
      const user = await select(
        UserModel.findById(input.id),
        selection: input.selection
      );

      return user;
    })
});

Frontend code:

import { withSelection } from 'trpc-selections';

const user = await withSelection(
  (selection) => appRouter.getUser.query({
    id: '<userId>',
    selection
  }),
  // `withSelection` takes a selection object containing the exact fields
  // you want to select from the `User` model
  {
    username: true,
    fullName: true,
    posts: {
      select: {
        title: true
      }
    }
  }
)

console.log(user); // Outputs: "{ username: '...', email: '...', posts: [{ title: '...' }, ...] }"

Selection hashes

To avoid DoS attacks from users passing arbitrarily complex selection objects to your route, trpc-selections provides a helper function called generateHashes that statically extracts all the inline selection objects throughout your entire codebase using ripgrep and AST parsing.

trpc-selections's People

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.