GdthG
tRPC3y ago
Gdth

Infering query/mutation callback opts parameter

Hey 🙂

Thanks for your hard work on this awesome library.
I want to create tRPC router, but i want to pass query (or mutation) callback from other part of the app. I am working with monorepo, and trpc router definition will be stored as a package shared by server (which will provide certain controllers implenetation) and frontend (which will infer type for queries & mutations). Unfortunately I don't know how to properly infer query / mutation parameter type:

Example:
import { fooZodSchema } from './foo.validators'

type Controllers = {
  // is it possible to infer opts properly?
  create: (opts: any) => {
    id: number
    name: string
  }
  // is it possible to infer opts properly?
  get: (opts: any) => {
    id: number
    name: string
  }
}

export const t = initTRPC.create()

export const fooRouter = (controllers: Controllers) =>
  t.router({
    create: t.procedure.input(fooZodSchema.create).query(controllers.create),
    get: t.procedure.query(controllers.get),
  })

export type FooRouter = ReturnType<typeof fooRouter>



I was playing around with it by myself, but I can't make it work. This was my attempt:

import { fooZodSchema } from './foo.validators'
import type { inferProcedureInput } from '@trpc/server'

type Controllers = {
  create: (
    opts: inferProcedureInput<FooRouter['_def']['procedures']['create']>
  ) => {
    id: number
    name: string
  }
  get: (
    opts: inferProcedureInput<FooRouter['_def']['procedures']['get']>
  ) => {
    id: number
    name: string
  }
}

export const t = initTRPC.create()

export const fooRouter = (controllers: Controllers) =>
  t.router({
    create: t.procedure.input(fooZodSchema.create).query(controllers.create),
    get: t.procedure.query(controllers.get),
  })

export type FooRouter = ReturnType<typeof fooRouter>


I assume it might be hard to infer due to fooZodSchema being passed as input (runtime evaluation), but I am sure some TypeScript wizards here will help:)
Was this page helpful?