What is the difference between Joi.object() and Joi.object().keys()?

Berry picture Berry · Nov 12, 2019 · Viewed 8.7k times · Source

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?

Answer

Luke Brown picture Luke Brown · Jun 24, 2020

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 using Joi.object().keys([schema]) is more useful when you want to add more keys (e.g. call keys() multiple times). If you are only adding one set of keys, you can skip the keys() method and just use object() 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