I am trying to generate Joi validations via code based on an object. I would like to know if there is a way to generate them programatically and store them into a file. I tried the following way:
Lets say I have an object as follows:
let obj = [{
Key: 'key1',
Type: 'string'
}]
A function to generate an object of Joi validations:
function getJoiObject(data) {
const obj = {};
Object.keys(data).forEach(key => {
if (data[key].Type === "string")
obj[data[key].Key] = Joi.string();
else if (data[key].Type === "integer")
obj[data[key].Key] = Joi.number();
else if (data[key].Type === "boolean")
obj[data[key].Key] = Joi.boolean();
});
return obj;
}
I saved the object onto a file and used it in another file for validations.
fs.writeFileSync('validations.json', JSON.stringify({res:getJoiObject(obj)}));
The problem is that when I import the validations.json into another file and validate it with data, it wouldn't work.
const a = {key1:'abc'};
Joi.object(validations.res).validate(a)
Could you please help.
Thanks in advance.