我需要创建动态架构来使用 Joi validator 在 node js
中验证我的 api 请求查询取决于请求查询中的键。假设下面提到的模式是我的有效查询。
我使用的是hapi/joi
版本16.1.8
组合1
{ type: 1, firstname: 'user first name', lastname: 'user last name'}
组合2
{ type: 2 , salary: 1000, pension: 200}
组合3
{ type: 3 , credit: 550, debit: 100}
正如您所看到的,对象键根据 type
的值而变化。如何正确处理?
我们可以使用 Joi.alternatives 处理两种情况喜欢
const schema = Joi.alternatives().conditional(Joi.object({ type: 1 }).unknown(), {
then: Joi.object({
type: Joi.string(),
firstname: Joi.string(),
lastname: Joi.string()
}),
otherwise: Joi.object({
type: Joi.number(),
salary: Joi.any(),
pension: Joi.any()
})
});
但是这如何在 3 个条件下完成呢?
最佳答案
我以稍微不同的方式实现了相同的目标。在这里发布相同的内容,因为这可能对将来的人有用。
const schema = Joi.object({
type: Joi.number().required().valid(1, 2, 3),
firstname: Joi.alternatives().conditional('type', { is: 1, then: Joi.string().required() }),
lastname: Joi.alternatives().conditional('type', { is: 1, then: Joi.string().required() }),
salary: Joi.alternatives().conditional('type', { is: 2, then: Joi.number().required() }),
pension: Joi.alternatives().conditional('type', { is: 2, then: Joi.number().required() }),
credit: Joi.alternatives().conditional('type', { is: 3, then: Joi.number().required() }),
debit: Joi.alternatives().conditional('type', { is: 3, then: Joi.number().required() }),
}))
这正如预期的那样完美地工作。
当类型值为1
时,对象应该只有type
、firstname
和lastname
当类型值为2
时,对象应该只有type
、salary
和pension
当类型值为3
时,对象应该只有type
、credit
和debit
任何其他组合都将作为错误从 joi 验证器中间件层抛出。此外,除 1、2 和 3 之外的任何其他类型值都将引发错误。
关于javascript - Joi 验证器条件模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59861503/