T
tRPC

How can I access the trpc context in zod's refine function?

How can I access the trpc context in zod's refine function?

Mmichaelschufi5/7/2023
To do something like
create: myProcedure
.input(myInputSchema.refine(async ({ slug }, ctx) =>
slugDoesNotAlreadyExist(ctx.db, slug),
{
message: 'Slug already exists',
path: ['slug'],
}))
.mutation(async ({ ctx, input }) => {
return ctx.db.insert(...)
}),
create: myProcedure
.input(myInputSchema.refine(async ({ slug }, ctx) =>
slugDoesNotAlreadyExist(ctx.db, slug),
{
message: 'Slug already exists',
path: ['slug'],
}))
.mutation(async ({ ctx, input }) => {
return ctx.db.insert(...)
}),
Edit: It would allow for easier UX because I can use the existing validation code in the frontend to show the user the errors at the correct field.
Nnlucas5/7/2023
You can’t, validators validate data in place and are generally 3rd party libs. You probably want a middleware after the input to then take the ID and check it exists
Mmichaelschufi5/7/2023
Okay, thank you. I guess I'll do it on field change in the frontend then. I think that's better for UX anyway.

Looking for more? Join the community!

T
tRPC

How can I access the trpc context in zod's refine function?

Join Server