0

My request body can be a single JSON object or array of JSON objects:

Single JSON Object

{
   "name" : "item 1",
   "description" : "item 1 description"
}

Array of JSON Object

[{
   "name" : "item 1",
   "description" : "item 1 description"
}, {
   "name" : "item 2",
   "description" : "item 2 description"
}
]

I want to validate these cases via celebrate/Joi

export const Create = celebrate({
    [ Segments.BODY ]: Joi.any() // how can I handle them here
});

2 Answers2

1

How to tell if item is array or object, using vanilla JavaScript:

    const arrayOrObject = (item) => {
      if (item instanceof Array) return ‘array’;
      else if (item instanceof Object) return ‘object’;
      return null;
    }

A similar "array or object" test using Joi:

    const Joi = require('@hapi/joi');

    const isArray = (item) => !Joi.array().validate(item).error;
    const isObject = (item) => !Joi.object().validate(item).error;

    let arr = [1,2,3];
    console.log(isArray(arr));  // true
    console.log(isObject(arr)); // false

    obj = {foo: "bar"};
    console.log(isArray(obj));  // false
    console.log(isObject(obj)); // true
terrymorse
  • 6,771
  • 1
  • 21
  • 27
  • Thanks for your response, but I need to do it with **Joi**. – Arman Kostandyan Feb 14 '20 at 11:32
  • Okay, I added a very simple `Joi` method. Is that what you are seeking? If you need to do further validation, you could first do the "array-or-object" test, then choose the appropriate validator schema (object or array of objects). – terrymorse Feb 14 '20 at 16:02
  • thanks again, I can do it in this way, but I would prefer to do it with Celebrate(https://www.npmjs.com/package/celebrate), all my validations are handled in that way. If you can help with it I would be most grateful)) – Arman Kostandyan Feb 17 '20 at 07:25
1

You can try the following -

const obj = {
   name: Joi.string(),
   description: Joi.string()
}

const joiObj = Joi.object(obj);

const joiArray = Joi.array().items(joiObj);

const joiSchema = Joi.alternatives().try(joiObj, joiArray);

const result = joiSchema.validate(payload);

if(result.error) {
  throw(result.error);
}


return payload;

You might have to work the error response (result.error) in order to get the desired error message for the API consumer but that's about it.

Let me know if this helps!

saurabh
  • 601
  • 6
  • 8