Is There A Way To Merge Joi Schemas?

Undistraction picture Undistraction · Mar 20, 2017 · Viewed 8.6k times · Source

Is there any way to merge two joi schemas into a single schema?

Schema 1

{
  alpha: Joi.number().required(),
  beta: Joi.string().required(),
  chalie: Joi.object({
    xray: Joi.number().required(),
  }).required()
}

Schema 1

{
  delta: Joi.string().required(),
  echo: Joi.number().required(),
  charlie: Joi.object({
    zulu: Joi.string().required(),
  }).required()
}

Merged Schema:

{
  alpha: Joi.number().required(),
  beta: Joi.string().required(),
  chalie: Joi.object({
    xray: Joi.number().required(),
    zulu: Joi.string().required(),
  }).required()
  delta: Joi.string().required(),
  echo: Joi.number().required(),
}

Without nested objects it's easily done with Object.assign, but even a deep object merge won't work with the nested objects because the nested object is a function call.

Answer

szanata picture szanata · Jun 25, 2019

I was wondering the same thing, as I wanted to merge two different schemas, and found this: https://github.com/hapijs/joi/blob/v9.0.4/API.md#anyconcatschema

const a = Joi.string().valid('a');
const b = Joi.string().valid('b');
const ab = a.concat(b);

Hope that helps you