RealityShift
RealityShift14mo ago

Generic Zod as Input Type

I'm not positive if this is a TRPC question, typescript in general, or failure to understand Zod in this usecase. Our API has a several endpoints that all work the same way just pass in different payloads. I'm trying to create a single function to assign to all my TRPC routes:
enum Endpoint {
"Person" = "/users/person",
"Company" = "/core/company",
}

update: createTRPCRouter({
person: updateGeneric(ZPersonUpdate, Endpoint.Person),
company: updateGeneric(ZCompanyUpdate, Endpoint.Company),
})

function createUpdateApiProcedure<T extends z.SomeZodObject>(schema: T, path: Endpoint) {
return protectedProcedure.input(
z.object({id: z.number()}).extend(schema)
).mutation(async ({ ctx, input }) => {
//call api with payload
})
}
enum Endpoint {
"Person" = "/users/person",
"Company" = "/core/company",
}

update: createTRPCRouter({
person: updateGeneric(ZPersonUpdate, Endpoint.Person),
company: updateGeneric(ZCompanyUpdate, Endpoint.Company),
})

function createUpdateApiProcedure<T extends z.SomeZodObject>(schema: T, path: Endpoint) {
return protectedProcedure.input(
z.object({id: z.number()}).extend(schema)
).mutation(async ({ ctx, input }) => {
//call api with payload
})
}
I'm not sure what should be in the input section to make this work?
2 Replies
Nick
Nick14mo ago
You want a Router Factory, and potentially the polymorphism utilities I have a dev.to post on it if you google for “trpc router factories” but it’s a more advanced topic so we don’t really push this in the docs Inputs themselves can’t be generic though, you need to have multiple routers
RealityShift
RealityShiftOP13mo ago
Got it thanks Nick!