Search code examples
javascriptnode.jsjoi

How to re-use existing Joi schema properties?


I have the following schema:

const baseSchema = Joi.object({
  a: Joi.string().trim().empty(null, ''),
  b: Joi.string().guid().empty(null),
})
  .xor('a', 'b')
  .messages({
    'object.missing': 'One of "a", "b" is required.',
    'object.xor': 'Only one of "a", "b" is allowed.',
  });

I want to create another schema that includes only the properties of the baseSchema (without the 'xor' dependency and messages).

The extended schema should look like:

const extendedSchema = Joi.object({
  a: Joi.string().trim().empty(null, ''),
  b: Joi.string().guid().empty(null),
  c: Joi.string().trim(),
})
  .xor('a', 'b', 'c')
  .messages({
    'object.missing': 'One of "a", "b", "c" is required.',
    'object.xor': 'Only one of "a", "b", "c" is allowed.',
  });

I tried using both the keys() and append() methods but these end-up duplicating the 'xor' dependency and messages as well.


Solution

  • You can use object.keys([schema])

    const baseSchema = Joi.object({
      a: Joi.string().trim().empty(null, ''),
      b: Joi.string().guid().empty(null),
    });
    
    const extendedSchema = baseSchema.keys({
        c: Joi.string().trim()
    });
    
    const firstSchema = baseSchema.xor('a', 'b')
      .messages({
        'object.missing': 'One of "a", "b" is required.',
        'object.xor': 'Only one of "a", "b" is allowed.',
      });
    
    const secondSchema = extendedSchema.xor('a', 'b', 'c')
      .messages({
        'object.missing': 'One of "a", "b", "c" is required.',
        'object.xor': 'Only one of "a", "b", "c" is allowed.',
      });