Search code examples
node.jsjoi

Add key in Joi object if key does not exist


I have a joi schema like this

Joi.object({
  name: Joi.string(),
  language: Joi.string(),
  birthday: Joi.date(),
  age: Joi.number().integer()
})

The input can contain birthday and age at the same time or just one of the keys. If one of the keys does not exist, I want the missing key to be automatically added with the string "NULL" like this

//input
{
 "name": "Jane Doe",
 "language": "de",
 "birthday": "1960-06-27"
}
//modified to
{
 "name": "Jane Doe",
 "language": "de",
 "birthday": "1960-06-27",
 "age": "NULL"
}

Is there a way to automatically add a key with a default value, if the key is missing?


Solution

  • Use any.default([value]):

    const schema = Joi.object({
      name: Joi.string(),
      language: Joi.string(),
      birthday: Joi.date(),
      age: Joi.number().integer().default(null)
    });
    
    console.log(schema.validate({
      "name": "Jane Doe",
      "language": "de",
      "birthday": "1960-06-27"
    }));
    

    Output:

    {
      name: "Jane Doe",
      language: "de",
      birthday: Mon Jun 27 1960 01:00:00 GMT+0100 (Central European Standard Time),
      age: null
    }
    

    I would prefer null rather then a string "NULL" because both date and age are not of type string.