Skip to content

Idea: query/mutation options similar to Fastify's route configs #1731

Description

@LouisHaftmann

It would be nice to have some sort of per query/mutation options, just like Fastify's route configs

Could work like this:

router<Context>({ hasAuth: true } /* default options, also used for type inference */)
  .middleware(async ({ options }) => {
    /* only check if route has auth */
    if(options.hasAuth === true) {
      // check auth
    }
  })
  .mutation('login', {
    input: ...,
    /* optional options object */
    options: { 
      hasAuth: false
    },
    resolve: ...
  })

Possible use cases:

  • disable authentication on a per route basis
  • rate limiting settings per route
  • ...

Activity

  1. changed the title [-]query/mutation options similar to Fastify's route configs[/-] [+]Idea: query/mutation options similar to Fastify's route configs[/+] on Apr 5, 2022
  2. KATT commented on Apr 5, 2022

    @KATT
    Member

    Hey, great idea! I've been toying with a similar idea to decorate procedures with metadata, similarly useful for #1724 to distinguish that a certain mutation would be a PUT or DELETE in the OpenAPI-output.

    How I would like to see this designed in terms of usage:

    // ./src/server/createRouter.ts
    import { Context } from './context';
    import * as trpc from '@trpc/server';
    
    interface Meta {
      hasAuth?: boolean;
    }
    
    export function createRouter() {
      return trpc.router<Context, Meta>();
    }
    // src/server/routers/post.ts
    import { Prisma } from '@prisma/client';
    import { z } from 'zod';
    import { createRouter } from '~/server/createRouter';
    import { prisma } from '~/server/prisma';
    
    export const postRouter = createRouter()
      .mutation('add', {
        input: z.object({
          id: z.string().uuid().optional(),
          title: z.string().min(1).max(32),
          text: z.string().min(1),
        }),
        // this is optional:
        meta: {
          hasAuth: true,
        },
        async resolve({ input }) {
          const post = await prisma.post.create({
            data: input,
          });
          return post;
        },
      })

    When using it:

    // Check meta for `post.add`
    
    const postAddMeta = appRouter._def.mutations['post.add'].meta.hasAuth

    Notes:

    • Meta needs to extend Record<string, any> and default to {}
    • Meta is optional on each procedure
  3. LouisHaftmann commented on Apr 5, 2022

    @LouisHaftmann
    ContributorAuthor

    wouldn't it be easier if meta was available in the middleware args?

    .middleware(async ({ meta }) => {
        if(meta.hasAuth === true) {
          ...
        }
      })
  4. KATT commented on Apr 5, 2022

    @KATT
    Member

    It could be available in the middleware as well

  5. linked a pull request that will close this issuefeat(server): route metadata #1736on Apr 6, 2022
  6. LouisHaftmann commented on Apr 7, 2022

    @LouisHaftmann
    ContributorAuthor

    In the future we should add a way of changing the meta type from middleware. This would make it easier for plugin devs to add custom route options.

  7. LouisHaftmann commented on Apr 7, 2022

    @LouisHaftmann
    ContributorAuthor

    This would also work:

    router<Context, TMeta & TPlugin1 & TPlugin2>().middleware(plugin1).middleware(plugin2)
  8. LouisHaftmann commented on Apr 7, 2022

    @LouisHaftmann
    ContributorAuthor

    i really like this approach

    const plugin = router<any, { meta2: boolean }>().middleware(({ next }) => {
      return next();
    });
    
    router<any, { meta1: string }>().plugin(plugin)

    We would need a function (router.plugin()) similar to router.merge() that also merges context and meta

  9. reopened this on Apr 7, 2022
  10. KATT commented on Apr 7, 2022

    @KATT
    Member
  11. TheBestMoshe commented on Apr 11, 2022

    @TheBestMoshe

    With this new feature, is there any way to get Context Swapping to work?

    For example, if the hasAuth meta parameter is true, the middleware will check to make sure the user has a token. Now that this check was done, the resolver should know the the token is nonnullable.

    Note: Example code is from a Next.js codebase

    Context

    import * as trpc from "@trpc/server";
    import * as trpcNext from "@trpc/server/adapters/next";
    import { getToken } from "next-auth/jwt";
    import { env } from "../utils/env/serverEnv";
    
    export const createContext = async ({
      req,
      res,
    }: trpcNext.CreateNextContextOptions) => {
      const token = await getToken({
        req,
        secret: env.JWT_SECRET,
      });
    
      return {
        req,
        res,
        token,
      };
    };
    
    export type Context = trpc.inferAsyncReturnType<typeof createContext>;

    Router

    type Meta = {
       hasAuth: boolean
    }
    
    trpc.router<Context, Meta>().middleware(async ({ meta, ctx }) => {
        if(meta.hasAuth && (!ctx.token || !verifyTokenIsValid(ctx.token))) {
          throw new TRPCError({ code: "UNAUTHORIZED" });
        }
    
          return next({
            ctx: {
              ...ctx,
              token: ctx.token, // At this point, `ctx.token` is still nullable because `meta.hasAuth` can be false, which means there does not need to be a token.
            },
          });
      })
      .mutation("test", {
        meta: {
          hasAuth: true
        },
        async resolve({ ctx }) {
          ctx.token // Here, `ctx.token` should not be nullable because the middleware will reject any requests that do not have a token.
        },
      });

    Using this pattern, the token in the resolver is still nullable. Is there any way that tRPC can infer the values of ctx based on how the middlewares affect the ctx based on the code flow which is controlled by the meta object?

    If the example code is not clear enough, I can make a full example that reproduces this.

  12. github-actions commented on Oct 4, 2022

    @github-actions
    Contributor

    This issue has been locked because it had no new activity for 14 days. If you are running into a similar issue, please create a new issue. Thank you.

  13. locked as resolved and limited conversation to collaborators on Oct 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions