Repository navigation
Description
I want to transform a slug or id before passing it to the resolve function. Currently you cannot access the router ctx inside the input function which has the downside that you have to do transformations inside the resolve function (if the transformation requires the ctx object).
For example: You have a user profile page (profile/{userId}) that uses trpc to get the profile data of a user. You pass this userId to trpc and want to convert the userId into a user object by utilizing some kind of UserRepository that is available on your ctx object. The UserRepository is an instance of a service, and cannot be accessed without the ctx object as you do not allow singletons.
By allowing the input to access the ctx we can utilize Zod's transform to convert a slug or id before it is passed to the resolve function. This way we can keep our resolve functions as clean as possible and keep any sort of input validation & transformation inside our input function.
According to the docs we can currently pass a Zod, Yup or superstruct object as input. I am not aware how this type is checked internally but if they all provide an object instead of a function we could allow a function as input with the ctx as an argument.
The end-result could look like:
.query('profile', {
input: ({ ctx }) =>
yup.object({
user: yup.number().required(),
})
.transform((userId) => ctx.userRepository.findById(userId))
.refine((user) => !!user, {
message: 'User could not be found.',
}),
resolve({ input }) {
return {
username: input.user.username,
};
},
});Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsPotential breaking changes
Activity
jlalmes commentedon Jun 7, 2022
Hi @jrmyio.
The
inputvalidation should only be used for parsing request input (e.g. check thatuserIdis defined and is anumber). Any data fetching or additional logic should be placed inside yourresolvefunction, which has access toctx.Hope this makes sense!
jrmyio commentedon Jun 7, 2022
Imo, a user Id that doesn't exist in the database can be considered bad input just like a non-number userId is.
Yes, in my example I am using
z.transform()but there are other use-cases like usingz.enum(). Let's say my trpc calls supports alocaleparameter. The available locales can be accessed from myctx. For example:ctx.locales = ['en', 'de', 'fr'];In order to validate the input I need to check the
ctx.localesso I can usez.enum(ctx.locales). This should clearly be a use-case where you do not want this check to be inside your resolve function.So my questions would be:
inputto only check things that don't require context?ctxinside input?resolvefunction with more input validation?jlalmes commentedon Jun 7, 2022
Hi @jrmyio.
It looks like the use-case you mentioned above is best suited to the
.middleware(...)utility. You can read more about it here: https://trpc.io/docs/middlewares#raw-input.Let me know what you think!
jrmyio commentedon Jun 7, 2022
I suspect
middlewarenot to be on a per-route level. For a parameter calledlocaleI can see how that would always be the same as this could be a reserved parameter for your application.But let's say I want a messaging system. The message mutation would have a parameter called
receiver, notuser. There is no way you would catch all use-cases into a top level middleware nor would that be good practice.But this also highlights another reason why it's so useful to have smart
ctxaware inputs. One could create aUserInputsimilar to my original-post and then reuse that in themessagemutation for thereceiver.I love the abstraction trpc is doing where there is clearly a separation between
inputandresolve, and I would love to keep it that way. I want myresolvefunctions not to deal with additional checks or transformations (note how many MVC frameworks also support input transformation before it hits the 'code' of the controller, example Symfony).Zod seems to have the support for transformations, the types even change when using
.transform(). This is really powerful, especially for the use-cases mentioned above.KATT commentedon Jun 8, 2022
I am tentatively positive to this suggestion, but we should not consider it until we have an alpha of the next major.
The next major's design would probably allow for creating a custom input parser that allowed this as the inputs will just be an abstraction on top of middlewares...
trpc/packages/server/src/router.ts
Lines 302 to 304 in 0616ba5
[-][Feature Request] Add a way to access the 'ctx' in the 'input' definition[/-][+]Add a way to access the `ctx` in the `input` parsers[/+]KATT commentedon Jul 10, 2022
With the new major we could potentially add a new method called
.inputCallbackor similar that could take whateverinputtakes but as a callback instead. 🤔jrmyio commentedon Jul 11, 2022
Is the input expecting a function in its default behavior? If not, wouldn't it be possible to overload
inputby allowing a function as the first parameter?KATT commentedon Jul 11, 2022
@sachinraja - a penny for your thoughts; do you think there's a way to support both?
We could change the default behavior of the parser callback from
inputParser( input: unknown ) { }toinput( opts: { rawInput: unknown; ctx: Context })maybe?27 remaining items
ochicf commentedon Jan 5, 2024
@lxia1220 +1 for option 2. Signature is consistent with resolver/middlewares, and also is the most flexible because it covers parser, parser creator and validator usages.
KATT commentedon Jan 6, 2024
I'm fine with option 2 but it'll break a bunch of adapters that work thanks to
ParserCustomValidatorEsque- you'll notice it when runningpnpm vitest validators.IIRC, effect, runtimes, and others will break which isn't ideal, so it'd need a good story on how to work with those
ironexdev commentedon Aug 30, 2024
I also have the use-case where I need to access context (specifically locale) in Input definition. This is my solution since experimental_standaloneMiddleware was deprecated.
src/trpc/routers/verification-tokens.ts
src/trpc/trpc.ts
const t = initTRPC...) availableL-Mario564 commentedon Oct 24, 2024
What's the current status of this issue? I've encountered a use-case in one of my projects where this feature would be great. I use the
mutation/querycallback to do additional validation with runtime values but it would be great to have this feature to separate validation logic from what the procedure is actually supposed to do.I may add that I'm also down to contribute with a PR if necessary.
michaelbrusegard commentedon Jan 14, 2025
I also would like something like this to access the current locale from the context for localised validation error messages
michaelbrusegard commentedon Jan 14, 2025
So one work around for translations, maybe not the cleanest solution. You can apply the translation function in the errorformatter, and instead just return the translation keys as error messages in the validation methods. Hopefully this helps if anybody has the same situation
KATT commentedon Jan 26, 2025
@michaelbrusegard you could likely use async local storage for this, see this test for inspo
michaelbrusegard commentedon Jan 26, 2025
That seems like a much cleaner solution to what I am currently doing. Thank you!
KATT commentedon Jan 26, 2025
But thinking about it - now that there's a standard schema, I think we can drop the use of callback functions and add support for this for real 👀
Looking at doing it now
michaelbrusegard commentedon Jan 26, 2025
That would be amazing! How long would you suspect it to take to implement? I am considering if it is worth implementing it with asyncLocalStorage in the meanwhile. Thank you for this amazing RPC solution!
KATT commentedon Jan 26, 2025
Pulled the plug on it, it was a bit too involved, might pick it up later or when/if people sponsor this issue 🙃
michaelbrusegard commentedon Jan 26, 2025
That is understandable, thanks for the heads up!
KATT commentedon Nov 2, 2026
🤖 In v12,
.input()also takes a callback that getsctxand returns the schema, e.g.t.procedure.input(({ ctx }) => z.object({ locale: z.enum(ctx.locales) })), so context-aware validation and transforms run in the input step, and invalid input is the procedure's typedBAD_REQUEST. The callback runs per call, so build what you can outside it. https://github.com/trpc/trpc/blob/v12/next/.agent-docs/decisions/validation.md. v12 isn't released yet and there's no ETA.