next-joi
next-joi copied to clipboard
Get converted payload after validation
Hello,
I am using next-joi with next-connect and it works great. I was wondering if there is a way for the request handler to receive the validated/converted payload.
For example:
const schema = Joi.object({
name: Joi.string().trim(),
number: Joi.number().integer(),
})
req.body = {
name: " dummy ",
number: "5",
}
const handler = nextConnect().post( validate({ body: schema }), async (req, res) => {
const { name, number } = req.body
// Here name and number are the original values
// I would like them to be "dummy" and 5 (name trimmed and number casted to int)
})
Hi, @JeffreySoriano5!
That's currently not possible, but it looks like a good idea to me :-) I will take a look at joi's documentation and hapi implementation to see if that's a good practice (I have some reservations about mixing together validation and "transformation").
Thanks for the quick response @sergioalvz. I understand your concern. Maybe it could be an option. It would be useful for things like the query search strings which are always parsed as string, for example for pagination. In this case I would have to call the validate inside of the handler again to get the casted/sanitized values.
Another thing to consider: as a TypeScript user, I would expect req.query or req.body to match the defined Joi schema -once the request gets converted. I don't know if that's possible, though...
as a TypeScript user, I would expect req.query or req.body to match the defined Joi schema
You can use my approach described in #13, or if you use next-connect, you can also use the generic from the call actions:
interface Body {
name: string,
number: number,
}
.post<{body: Body}>(validator({ body: schema }), async (req, res) => {
});
I was wondering if there is a way for the request handler to receive the validated/converted payload
From my pov that should be no problem, since the validation function returns the converted values by default.
I have some reservations about mixing together validation and "transformation"
We could add the possibility to pass an option object for the validation function of Joi to this middleware, because there is the convert field which allows to toggle the "transformation".