Controllers with JOI validation

  • npm i joi
  1. POST
    • Make controller without JOI
    • Import Joi to controller file and describe in SCHEMA required fields of the object waiting

      See the Pen 11 - JOI import & describe SCHEMA for object by Andrii (@imitator) on CodePen.

    • Then in function before all code validate req.body by

      const { error, value } = productSchema.validate(req.body);

    • So if we get required fields our code in function works as a usual, if something wrong, we get error and should process it by usual if () {}

      See the Pen 13 - POST with JOI validation by Andrii (@imitator) on CodePen.

    • P.S. For reusing productSchema somewhere else (f.e. for updating item) we may move schema from file controller to separate place, f. e. to utils/validate/product-joi.js
      const Joi = require('joi');
      const productSchema = Joi.object({
      name: Joi.string().min(2).required(),
      price: Joi.number().min(0).required(),
      });
      module.exports = productSchema;

      And in controller only import it by

      const productSchema = require('../../utils/validate/product-joi');