Joi validation not working for alternatives conditional schema with switch option

87 views Asked by At

I have the following Joi schema validation code:

const Joi = require('joi');

const baseTaskSchema = Joi.object({
  id: Joi.number().integer().required(),
  retailer_id: Joi.string().required(),
  crawler_id: Joi.string().required(),
  enable_multi_store: Joi.boolean(),
});

const searchTermsSchema = baseTaskSchema
  .keys({
    search_term: Joi.string().required(),
  })
  .unknown(true);

const categorySchema = baseTaskSchema
  .keys({
    retailer_category_id: Joi.string().required(),
    journey: Joi.string(),
  })
  .unknown(true);

const productSchema = baseTaskSchema
  .keys({
    retailer_product_id: Joi.string().required(),
    journey: Joi.string(),
  })
  .unknown(true);

const taskSchemaWithSwitch = Joi.object({
  task: Joi.alternatives().conditional('type', {
    switch: [
      {
        is: Joi.string().valid('category'),
        then: categorySchema,
      },
      {
        is: Joi.string().valid('detail'),
        then: productSchema,
      },
      {
        is: Joi.string().valid('search'),
        then: searchTermsSchema,
      },
    ],
  }),
});

I am trying to validate this JSON with the above schema.

{
  task: {
    id: 1,
    crawler_id: 'crawler_id',
    retailer_id: 'retailer_id',
    enable_multi_store: false,
    type: 'detail',
    retailer_product_id: '1234',
    search_term: null,
    journey: null,
    retailer_category_id: '',
  },
}

And I get the error [Error [ValidationError]: "task.retailer_category_id" is not allowed to be empty]

I do not see any proper syntax doing this with switch statements in Joi.

The same works with a schema just conditional statements with nested is then logic.

eg.

  Joi.object({ type: Joi.string().valid('category') }).unknown(true),
  {
    then: categorySchema,
    otherwise: Joi.alternatives().conditional(
      Joi.object({ type: Joi.string().valid('detail') }).unknown(true),
      {
        then: productSchema,
        otherwise: Joi.alternatives().conditional(
          Joi.object({ type: Joi.string().valid('search') }).unknown(true),
          {
            then: searchTermsSchema,
          }
        ),
      }
    ),
  }
);

This is the live code for playing around with the solution.

0

There are 0 answers