Reputation: 834
I have a post call which can take the payload as a single JS
object as well as array of objects to save it to the db. How to write a schema to validate against such payload ?
JS object
{
label: 'label',
key: 'key',
help_text: 'text'
}
Or
[
{
label: 'label1',
key: 'key1',
help_text:'text1'
},
{
label: 'label2',
key: 'key2',
help_text:'text2'
}
]
Upvotes: 0
Views: 1875
Reputation: 2998
You can accomplish this using Joi.alternatives(). Here is a working example:
const joi = require('joi');
var objectSchema = joi.object().keys({
label: joi.string().required(),
key: joi.string().required(),
help_text: joi.string().required()
}).unknown(false);
var arraySchema = joi.array().items(objectSchema);
var altSchema = joi.alternatives().try(objectSchema, arraySchema);
var objTest = {label: 'cuthbert', key: 'something', help_text: 'helping!'};
var arrTest = [
objTest
];
var failingArrTest = [
{
unknownProperty: 'Jake'
}
];
var result = joi.validate(objTest, altSchema);
var resultArrTest = joi.validate(arrTest, altSchema);
var resultFailingArrTest = joi.validate(failingArrTest, altSchema);
console.log(result);
console.log(resultArrTest);
console.log(resultFailingArrTest);
Upvotes: 5