简体   繁体   中英

How can I check if value is object or array of objects via Joi

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM