[英]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
錯誤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配置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.