Reputation: 2215
So I have a nested json something like below, which is a payload structure for api that I am writing
{"item_id":"1245",
"item_name":"asdffd",
"item_Code":"1244",
"attributes":[{"id":"it1","value":"1"},{"id":"it2","value":"1"}],
"itemUUID":"03741a30-3d62-11e8-b68b-17ec7a13337"}
My Joi validation on the payload is :
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, attributesArraySchema).optional()
})
}
where
const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().optional()
}).optional();
and
const attributeArraySchema = Joi.array().items(customAttributeObjectSchema).optional();
My question is : With the above Joi validation, if I edit my payload and send my attributes tag like below (i,e., with "values" as empty)
"attributes":[{"id":"CA1","value":""},{"id":"CA2","value":""}]
It throws an error saying:
"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"
]
What am I doing wrong here? What do I need to do if I need Joi to accept the below:
"attributes":[{"id":"CA1","value":""},{"id":"CA2","value":""}]
Upvotes: 0
Views: 1782
Reputation: 2215
So I resolved this by Changing the following schema definition from
const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().optional()
}).optional();
To
const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().allow('').allow(null)
}).optional();
Upvotes: 0
Reputation: 841
Do something like this
attributeArraySchema.customAttributes = [];
attributeArraySchema.customAttributes = [
{"id":"CA1","value":""},
{"id":"CA2","value":""}
];
Upvotes: 1