提问人:AnandShiva 提问时间:10/7/2023 最后编辑:AnandShiva 更新时间:10/7/2023 访问量:24
Joi 验证不适用于带有开关选项的替代条件架构
Joi validation not working for alternatives conditional schema with switch option
问:
我有以下 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,
}
),
}
),
}
);
这是用于尝试解决方案的实时代码。
答: 暂无答案
下一个:我怎样才能解决这个JOI问题
评论
retailer_category_id: Joi.string().allow('').required()
?retailer_category_id
retailer_category_id