I was working on a contract recently where there was a lot of JSON objects passed around from api to api. We investigated lots of validation methods for this type of thing. Simple key value || null sufficed for the simpler objects, however when object values were nested it got a bit tricky. Hence Joi.

Require the modul:

const Joi = require('joi');  

Create schema of each object:

const exampleSchema = Joi.object().keys({  
  a: Joi.string().required(),
  b: Joi.object().keys({ aa: Joi.string().required() }).required()
});

const contextSchema = Joi.object().keys({  
  statusCode: Joi.number().required(),
}).required();

const errorSchema = Joi.object().keys({  
  sterror: Joi.object().keys({
    errorno: Joi.number().required(),
  }).required(),
}).required();

Then use Joi validate method, passing in your object:

Joi.validate({ a: 'a string' }, exampleSchema, (error, value) => {  
    console.log('Error:', error);
    console.log('Valid:', value);
});

Joi.validate(undefined, contextSchema, (error, value) => {  
    console.log('Error:', error);
    console.log('Valid:', value);
});

Joi.validate({  
  statusCode: 201,
}, contextSchema, (error, value) => {
    console.log('Error:', error);
    console.log('Valid:', value);
});
Joi.validate({  
  error: ''
}, errorSchema, (error, value) => {
  console.log('Error:', error);
  console.log('Valid:', value);
});

Great to use. Next we will look at JSONSchema.