在 Joi 中如何处理嵌套?
How can I handle nested whens in Joi?
我试图期待一个像下面这样的对象,其中只有在未发送主要数据时才允许数据。
{
"action": {
"primary": "",
"data": {}
}
}
我试过这个模式:
Joi.object({
action: Joi.object({
primary: Joi.any(),
data: Joi.any(),
})
.when(Joi.object({
action: Joi.object({
primary: Joi.exist()
})
}), {
then: Joi.object({
primary: Joi
.string()
.required(),
data: Joi.any().forbidden()
}),
otherwise: Joi.object({
primary: Joi.any().forbidden(),
data: Joi.object()
.required()
})
})
});
它总是进入我的 otherwise
语句。其他语法也总是失败:.when('primary', { is: Joi.exist(), then:
当我尝试 .when('action.primary', { is: Joi.exist(), then:
时,Joi 本身出错 AssertionError [ERR_ASSERTION]: Item cannot come after itself: action
我可以建议以下重构吗?
Joi.object({
action: Joi.object({
primary: Joi.string(),
data: Joi.object().when("primary", {
is: Joi.exist(),
then: Joi.forbidden(),
otherwise: Joi.required()
})
})
});
它允许这两个对象:
{
action: {
data: {}
}
};
{
action: {
primary: "value"
}
};
注意:https://github.com/legraphista/joi-tester 是一个很酷的项目,无需设置应用程序即可验证 Joi 配置。
我试图期待一个像下面这样的对象,其中只有在未发送主要数据时才允许数据。
{
"action": {
"primary": "",
"data": {}
}
}
我试过这个模式:
Joi.object({
action: Joi.object({
primary: Joi.any(),
data: Joi.any(),
})
.when(Joi.object({
action: Joi.object({
primary: Joi.exist()
})
}), {
then: Joi.object({
primary: Joi
.string()
.required(),
data: Joi.any().forbidden()
}),
otherwise: Joi.object({
primary: Joi.any().forbidden(),
data: Joi.object()
.required()
})
})
});
它总是进入我的 otherwise
语句。其他语法也总是失败:.when('primary', { is: Joi.exist(), then:
当我尝试 .when('action.primary', { is: Joi.exist(), then:
时,Joi 本身出错 AssertionError [ERR_ASSERTION]: Item cannot come after itself: action
我可以建议以下重构吗?
Joi.object({
action: Joi.object({
primary: Joi.string(),
data: Joi.object().when("primary", {
is: Joi.exist(),
then: Joi.forbidden(),
otherwise: Joi.required()
})
})
});
它允许这两个对象:
{
action: {
data: {}
}
};
{
action: {
primary: "value"
}
};
注意:https://github.com/legraphista/joi-tester 是一个很酷的项目,无需设置应用程序即可验证 Joi 配置。