【发布时间】:2021-10-02 07:51:54
【问题描述】:
我想使用 Joi 来验证传入的 JSON 请求对象,以便每个数组元素在路径 .runs[].results.type 处具有相同的值。如果有一个元素突出,验证应该会失败。类似于array.unique 的对立面.results.type 内.runs[]。
将以下 JSON 想象为有效输入:
{
runs: [
{ results: { type: 'A', side: 'left' }, meta: { createdBy: 3 } },
{ results: { type: 'A', side: 'right' }, meta: { createdBy: 1 } }
]
}
这应该会引发验证错误:
{
runs: [
{ results: { type: 'A', side: 'left' }, meta: { createdBy: 3 } },
{ results: { type: 'B', side: 'right' }, meta: { createdBy: 1 } }
]
}
我尝试编写一个 Joi 架构,例如:
...
runs: Joi.array()
.min(1)
.items(
Joi.object()
.unknown()
.keys({
results: Joi.object()
.keys({
type: Joi.string()
.allow('A', 'B', 'C', 'D')
.valid(Joi.ref('....', { in: true, adjust: runs => runs.map(run => run.results.type) }))
.required(),
side: Joi.string().allow('left', 'right')
})
})
)
...
但这不起作用(我认为它以循环引用结束)。此外,即使它成功运行,我不确定如果提供了两种差异类型 A 和 B,它是否真的会破坏验证。
【问题讨论】:
标签: javascript node.js typescript validation joi