iway1 / trpc-panel

MIT License
627 stars 43 forks source link

Support Base Procedures #78

Open pachoclo opened 1 year ago

pachoclo commented 1 year ago

The problem

When using the base procedures pattern with merged input, trpc panel throws the following error:

trpc-panel: Failed to parse procedure <procedure-name>, Couldn't parse node.

When we get this error, the procedure does not show on the panel UI at all.

More Context

tRPC allows us to use base procedures to reuse procedure code and prevent repetition. One feature of base procedures--that is not clearly shown in the documentation example--is input schema merging: if a procedure declares its own (zod) schema and "extends" a base procedure that also declares its own input schema, tRPC merges those input schemas into one.

For example:

// base procedure
const adminProcedure = t.procedure
  .input(z.object({ adminId: z.string().cuid() }))
  .use((opts) => {
    if (!opts.input.adminId) {
      throw new TRPCError({
        code: 'UNAUTHORIZED',
        message: "No admin ID provided",
      })
    }
 
    return opts.next()
  })

export const appRouter = t.router({
  banUser: adminProcedure
  .input(z.object({ userId: z.string().cuid() }))
  .mutation(() => {
    ...
  }),
})

The procedure banUser "extends" the base adminProcedure. tRPC will resolve the input required for banUser by merging the two declared inputs, requiring both adminId and userId.