1

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.

Sai Raman Kilambi
  • 878
  • 2
  • 12
  • 29

1 Answers1

0

Joi has methods to serialize and deserialize its schemas, but they aren't fully documented (as of v17.6). I had a similar question and found this GitHub issue which answered it for me.

What you can do is call the describe() method on your schemas before saving them to a file. This will serialize them into a simpler form. Then, when reading the serialized version from your file, use Joi.build() and pass in your serialized schema to deserialize them back into Joi objects. Just make sure to parse stringified JSON back into an object first.

c0rb1n
  • 23
  • 1
  • 6