I have an api that resembles rpc calls in the form of this schema:
var whitelist = {
firstObject: ['method1', 'method2'],
secondObject: ['method1', 'method2']
};
var objects = Object.keys(whitelist);
var schema = Joi.object().keys({
object: Joi.string().required().valid(objects),
method: Joi.string().required()
})
Now I want to validate that
object is one of the keys of the whitelist, which already works.method is in the whitelist under the correct object entry but I'm not seeing how this could be achieved. I would appreciate any tips in the right direction.
I'm not following what you want to do. Can you post some examples of valid and invalid values?
Sure,
var whitelist = {
mario: ['run', 'jump'],
logger: ['print', 'log']
};
// Valid
{
object: 'mario'
method: 'run'
}
{
object: 'logger'
method: 'print'
}
// Invalid
{
object: 'mario'
method: 'print'
}
{
object: 'logger'
method: 'jump'
}
I hope these examples makes it a bit clearer.
var schema = Joi.object({
object: Joi.valid('mario', 'logger'),
method: Joi.when('object', {
is: 'mario',
then: Joi.valid('run', 'jump'),
otherwise: Joi.valid('print', 'log')
})
});
Thanks a lot for the quick answer! While this solves the issue in this toy example I'm gonna have probably five or more different objects. Is there any way to solve this a little more elegant than nesting these when conditions in one another?
No. At some point you have to write code.
Most helpful comment
No. At some point you have to write code.