getmeli / meli

Platform for deploying static sites and frontend applications easily. Automatic SSL, deploy previews, reverse proxy, and more.
Other
2.4k stars 97 forks source link

Stop using joi.alternatives #211

Open gempain opened 3 years ago

gempain commented 3 years ago

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.