According to Joi documentation, you can use Joi.object()
like so:
const object = Joi.object({
a: Joi.number().min(1).max(10).integer(),
b: Joi.any()
});
But you can also write an equivalent code using Joi.object().keys()
like so:
const object = Joi.object().keys({
a: Joi.number().min(1).max(10).integer(),
b: Joi.any()
});
What's the difference between the two?
If you're writing your schema once then you do not need to use .keys()
. As their docs say it is "useful" to use .keys()
when added more lines (keys) to your object.
Joi.object().keys([schema]) notation
This is basically the same as
Joi.object([schema])
, but usingJoi.object().keys([schema])
is more useful when you want to add more keys (e.g. callkeys()
multiple times). If you are only adding one set of keys, you can skip thekeys()
method and just useobject()
directly.Some people like to use
keys()
to make the code more explicit (this is style only).
Taken from: https://github.com/hapijs/joi/blob/v8.0.3/API.md#joiobjectkeysschema-notation
I also found this:
There are many ways to use joi. The hapi docs can't show everything. Calling keys() is only recommended when adding keys to an object as it creates another schema
Taken from: https://github.com/hapijs/hapi/issues/2222