问题
I want to do a validation with Joi in my body, but it seems never work and fall all the time in the same condition. So if i POST with this
endPoint: /elasticSearch?eType=scroll&scroll=1h
Body:{}
that supposed to throw an error, because eType is scroll and in this case scroll_id need to be required,not null, not empty.
even when i POST with this
endPoint: /elasticSearch?eType=search&scroll=1h
Body:{}
that supposed to throw an error, because eType is search and in this case query need to be required.
so with these codes,
in one case it just always pass like if it's had no validation even if they should not pass in my opinion and in the second case, i got error: query is required, and scroll_id is required all the time when i make a call.
so someone can help me to understand why these validation are wrong ?
Thanks
Update
By default, if i do that like this:
body:
{
query:
Joi.alternatives()
.when(Joi.ref('$query.eType'),
{
is: Joi.string().equal('search'),
then: Joi.required()
}
),
scroll_id:
Joi.alternatives()
.when(Joi.ref('$query.eType'),
{
is: Joi.string().equal('scroll'),
then: Joi.required()
}
)
}
That required query and scroll_id all time.
回答1:
Directly copied from documentation.
When using a Joi validation object, the values of the other inputs (i.e. headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).
So, use Joi.ref('$query.eType')
in your eType references, because you are trying to validate payload according to query parameters, in the validation phase, they are in separate scopes.
Joi.alternatives()
.when(Joi.ref('$query.eType'), {
is: Joi.string().equal('search'),
then: Joi.required()
})
来源:https://stackoverflow.com/questions/54467550/joi-multiple-when-condition