joi
joi copied to clipboard
joi.object().optional() doesn't accept empty object anymore?
Context
- node version: 14
- module version: 17.6.0
- environment (e.g. node, browser, native): node
- used with (e.g. hapi application, another framework, standalone, ...): standalone
- any other relevant information:
How can we help?
Hi,
I think I might be facing a breaking change from Joi version 12 to 17.6.0 where doing joi.object().optional() no longer supports me to pass the validation when having an empty object (without keys) like {}
Below is my failed validation, where i pass q={} and sort={}
{
"statusCode": 400,
"message": "Validation failed",
"errors": [
{
"message": "\"q\" must be of type object",
"path": [
"q"
],
"value": "{}"
},
{
"message": "\"sort\" must be of type object",
"path": [
"sort"
],
"value": "{}"
}
]
}
Any suggestion on how I should be handling this, as I don't know the keys by default (they're unknown) and is still fine if you pass an empty object like {} ?
q: joi.object().optional(),
sort: joi.object().optional(),
Can't say it's reproducible https://runkit.com/embed/kt9ta42pxzbq
const querySchema = {
query: joi.object().keys({
q: joi.object().optional(),
sort: joi.object().optional(),
}),
};
...
router.get(
'/',
validate(querySchema),
This is how I do and then i get the validation error when doing a post http://dazzler.minikube/api/management/v2/users?q={}&sort={}
"statusCode": 400,
"message": "Validation failed",
"errors": [
{
"message": "\"q\" must be of type object",
"path": [
"q"
],
"value": "{}"
},
{
"message": "\"sort\" must be of type object",
"path": [
"sort"
],
"value": "{}"
}
]
}```
Oh, this is a query string. Then I guess you should read the 16.0.0 release notes, specifically the part about Array and object string coercion
.
Thanks for the replies @Marsup . I understood that I could restore the old behaviour in this case, but what would be the path to support objects in query string with our current joi in this case? Maybe I should adapt so I don't keep legacy code.
You mean if you want it globally? You should create a custom joi and share it across the app.
I feel like we're done here, reopen if you still need help.