Sorry this is probably a really stupid question but I just can't figure it out and can't find the answer on stackoverflow or by googling.
My request is a JSON object where the keys are IDs (therefore completely dynamic) but the values of said keys is a specific object, so for instance
{
"an-id": {
"name": "John",
"email": "[email protected]"
},
"another-id": {
"name": "Paul",
"email": "[email protected]"
}
}
Obviously if it were an array of objects it'll just be
const objectSchema = Joi.object().keys({
name: Joi.string().required(),
email: Joi.string().email().required(),
});
const usersArray = Joi.array().items(objectSchema).required();
so I thought maybe something like Joi.object().items(objectSchema).required() but obviously that doesn't work.
I assume this is very doable and I'm just being really stupid.
I think you want something like
Joi.object().pattern(/\w/, Joi.object().keys({
name: Joi.string(),
email: Joi.string().email()
}))
The patterns basically states that for the top object any key must match \w (which is just any word) and the value of that key must be the schema
see https://github.com/hapijs/joi/blob/master/API.md#objectpatternregex-schema
Ah! That makes perfect sense, I missed that one. Thanks. 馃憤
Np glad I could help!
Most helpful comment
I think you want something like
The patterns basically states that for the top object any key must match \w (which is just any word) and the value of that key must be the schema
see https://github.com/hapijs/joi/blob/master/API.md#objectpatternregex-schema