meli icon indicating copy to clipboard operation
meli copied to clipboard

Stop using joi.alternatives

Open gempain opened this issue 4 years ago • 0 comments

It's doesn't provide exploitable error messages. Instead, use

const joi = require('joi');

const schema = joi.object({
    type: joi.string(),
  })
  .when('.type', {
    is: 'a',
    then: joi.object({
      prop: joi.string()
        .required(),
    }),
  })
  .when('.type', {
    is: 'b',
    then: joi.object({
      prop: joi.number()
        .required(),
    }),
  });

const res = schema.validate({
  type: 'b',
  prop: 'a',
});

console.log(res);

Using . before type allows having the type property at the same level as all other properties, hence not having to use a sub property for the polymorphism.

gempain avatar Mar 19 '21 16:03 gempain