re: Joi — awesome code validation for Node.js and Express VIEW POST

FULL DISCUSSION
 

I personally use Joi to validate my REST API routes. Each route has a controller, responsible for getting the user request parameters. That controller then passes those params to a service. On that service i have a Joi validation that looks like this:

   async function create(data) {
      return Joi.validate(data, schemas.accountCreation, async (err, value) => {
         if (err) {
            return {
               success: false,
               message: err.message,
               status: 400
            }
         }

         //service logic....        

      }
   }

Each validation is stored in a file that can be reused across all application/microservice. It looks like this:


module.exports = {
    user: {
        accountCreation: Joi.object().keys({
            firstname: Joi.string().min(1).required(),
            lastname: Joi.string().min(1).required(),
            email: Joi.string().regex(EMAIL_REGEX).email().required(),
            password: Joi.string().regex(/^[\x20-\x7E]+$/).min(8).max(72).required()
        }),
        authentication: Joi.object().keys({
            email: Joi.string().regex(EMAIL_REGEX).email().required(),
            password: Joi.string().regex(/^[\x20-\x7E]+$/).min(8).max(72).required()
        })
    },
    collection: {
        create: Joi.object().keys({
            collectionName: Joi.string().regex(ascii).min(1).max(30).required(),
            fields: Joi.array().min(1).required(),
            fieldsToShow: Joi.number().min(1).optional()
        }),
        getCollectionsByOwner: Joi.string().uuid().required(),
        getCollectionsById: Joi.string().uuid().required()
    },
    items: {
        create: Joi.object().keys({
            collectionId: Joi.string().uuid().required(),
            image: Joi.optional(),
            fields: Joi.object({}).min(1).required().unknown()
        }).unknown(),
        getById: Joi.string().uuid().required(),
        deleteItemByUUID: Joi.string().uuid().required()
    }
}

 
code of conduct - report abuse