Hapi-Joi validate payload which can be a Array of objects or just simple Javascript object?

1.8k views Asked by At

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'
 }
 ]
1

There are 1 answers

1
Cuthbert On BEST ANSWER

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);