Ability to mutate/extend `input` from middlewares
Hi
I have a global middleware that should run for every route. This middleware simply coerces
''
(empty string) to undefined
for the whole input
object.
Here is my setup:
the function coerceEmptyStringsToUndefined
is guarnteed to work as expected. Here is the implementation btw:
The problem: this code throws a validation error
The error is from zod
which is: {received: '""', expected: 'number'}
.11 Replies
This sounds like a hack
Why not just fix the data being sent to the API?
And what’s wrong with defining your inputs in each procedure? Much easier to maintain if you don’t have global behaviour
Zod has coerce by the way, might also be a fix for your actual types
This would be an overhead. In my application, empty strings are considered as
undefined
. Using something like sendDataToTrpcRoute({ a: a === '' ? undefined: a})
for every piece of data is not a good solution for meWell Zod has tools to let you manipulate stuff. Coerce and Preprocess are likely what you want. Maybe refine/suoerRefine/transform too
You could define some custom string type that you use instead of z.string()
I still think that mutating
input
is the responsibility of trpc
. A lot of web frameworks allow you to mutate the input passed. Trpc itself lets you extend the context
. Implementing it for input
would be convenient as well.
This idea will introduce the same overhead, that is, I have to change every schema to transform
to coerce empty strings to undefined.Well I think you can already do this, it’s just a bad idea
I have to mention that I like TRPC and since I have used I didn't use any other approach for backend routes. Just to be clear.
Pretty sure you can chain input calls
It would be nice if you can provide a sample code that works for my case
Have a look at how our input parser works internally, it’s just a middleware to begin with
.input() isn’t real
So here is what i found. tldr: none of the functions are exported for external use.
There is a function called
createNewBuilder
It does what i want, but it is not exported for external use.
There are some other functions that could help (for example, createResolver
to create a custom reoslver with my middlewares applied), but I was not able to import them.GitHub
trpc/packages/server/src/unstable-core-do-not-import/procedureBuild...
🧙♀️ Move Fast and Break Nothing. End-to-end typesafe APIs made easy. - trpc/trpc
Currently, there is no way to implement this functionality outside
@trpc/server
package. I do not have time to work on this.
But if you have a working approach I would be more than happy.
For now, i will fix the data before sending it to trpc
Is there any hope that this will be a feature request or something? I would appreciate this