As I work on my API, I encounter a nested JSON structure that serves as the payload for the endpoint. Here is an example of what it looks like:
{"item_id":"1245",
"item_name":"asdffd",
"item_Code":"1244",
"attributes":[{"id":"it1","value":"1"},{"id":"it2","value":"1"}],
"itemUUID":"03741a30-3d62-11e8-b68b-17ec7a13337"}
When it comes to validating this payload using Joi, here is what my validation logic looks like:
validate: {
payload: Joi.object({
item_id: Joi.string().required(),
item_name: Joi.string().required(),
placeId: Joi.string().allow('').allow(null),
itemUUID: Joi.string().allow('').allow(null),
item_Code: Joi.string().required().allow(null),
attributes: Joi.alternatives().try(attributeObjectSchema, attributeArraySchema).optional()
})
}
In the validation process, I define two schemas. The first one caters to individual attributes as objects, and the second one handles arrays of attributes:
const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().optional()
}).optional();
The second schema, which deals with arrays of attributes, looks like this:
const attributeArraySchema = Joi.array().items(customAttributeObjectSchema).optional();
Now, if I attempt to send a payload where all values in the "attributes" array are empty, Joi throws an error message:
"message": "child \"attributes\" fails because [\"attributes\" must be an object, \"attributes\" at position 0 fails because [child \"value\" fails because [\"value\" is not allowed to be empty]]]",
"validation": {
"source": "payload",
"keys": [
"attributes",
"attributes.0.value"
]
This error prompts me to reevaluate my validation criteria. How can I modify my Joi validation code to accept a payload where attribute values are empty strings like so:
"attributes":[{"id":"CA1","value":""},{"id":"CA2","value":""}]