Hapi-Joi 验证可以是对象数组或只是简单的 Javascript 对象的有效负载?

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

我有一个 post 调用,它可以将有效载荷作为单个 JS 对象以及对象数组将其保存到数据库中。如何编写模式来验证此类有效负载?

JS对象

{
  label: 'label',
  key: 'key',
  help_text: 'text'
}

或者

[
{
  label: 'label1',
  key: 'key1',
  help_text:'text1'
 },
 {
  label: 'label2',
  key: 'key2',
  help_text:'text2'
 }
 ]

您可以使用 Joi.alternatives() 完成此操作。这是一个工作示例:

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