A better way to handle pre-processed bodies by zod / joi / yup / ajv #656
Unanswered
GerbenRampaart
asked this question in
Q&A
Replies: 1 comment 1 reply
-
I had the same issue. Any idea why the Request class was designed with the |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I use Zod in a middleware to pre-validate the submitted bodies. However I found no consistent way to handle pre-parsed bodies with just the request.body property. To illustrate, here's how I've solved it.
The Zod middleware:
Let's say I have this Zod schema:
I can add the Zod middleware before the route:
And then the route looks like this:
This works, the body is nicely typed AND validated, and the validation, schema and route handling are nicely separated.
The only thing that bothers me a bit obviously is the line
ctx.state.validatedBody
I don't want to put the validated body on the state object. I want it to be on the request object.
Would it be possible to have maybe a nullable property on the request where the user can store a validated or resolved body?
Currently the place we await the body resolving must also be the place you use it.
Or am I missing a natural way this can already be done?
Beta Was this translation helpful? Give feedback.
All reactions