Joi 验证不适用于带有开关选项的替代条件架构

Joi validation not working for alternatives conditional schema with switch option

提问人:AnandShiva 提问时间:10/7/2023 最后编辑:AnandShiva 更新时间:10/7/2023 访问量:24

问:

我有以下 Joi 架构验证代码:

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,
      },
    ],
  }),
});

我正在尝试使用上述架构验证此 JSON。

{
  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: '',
  },
}

我收到错误[Error [ValidationError]: "task.retailer_category_id" is not allowed to be empty]

我没有看到任何正确的语法在 Joi 中使用 switch 语句执行此操作。

这同样适用于架构,只是带有嵌套的条件语句是逻辑。

例如。

  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,
          }
        ),
      }
    ),
  }
);

这是用于尝试解决方案的实时代码

JavaScript 快乐的.js JOI

评论

0赞 cmgchess 10/7/2023
retailer_category_id: Joi.string().allow('').required()?
0赞 AnandShiva 10/7/2023
理想情况下,它甚至不应该成为最终验证架构的一部分,因为我已经编写了开关逻辑来忽略它。并且不应该是 '' 表示 type:'category'。所以我也不能做出改变retailer_category_idretailer_category_id

答: 暂无答案