Middlewares

  1. Additional schema category checking (middleware for checking only category) could be before asking in Model schema of MongoDB. Actually if we write very good mongoDb model schema, we don't need to write additional schema check, but we have to know about this. This kind of checking makes with JOI f.e.
    • Make middleware file middlewares\newCategoryValidate.js
    • Install Joi if you don't do it before npm i joi
    • Make function (in our example it is "validateCategory") that take data and due to JOI help return error if error will be.
    • Make middleware (in our example it is "categoryValidateMiddleware" that use function in the previous point).
    • See the Pen 32__JOI-schema__used as a middleware by Andrii (@imitator) on CodePen.

    • Make reexports from middlewares folder in \middlewares\index.js if needed
      const categoryValidateMiddleware = require('./newCategoryValidate');
      module.exports = {
      categoryValidateMiddleware,
      };
    • Use categoryValidateMiddleware in routes

      See the Pen 33__use Joi middleware in routes by Andrii (@imitator) on CodePen.

  2. More universal middleware than Additional schema category checking is some kind of validateSchemaMiddleware, that could handle category, user, etc. checking. Means that we use one middleware for checking different schemas.
    • Create joiCategoryHandler - middlewares\joiHandlersWithSchemas\joiCategoryHandler.js, (it could be crated anywhere else, f.e. in utils or in helpers, but in this example we created in middleware folder)

      See the Pen 34__joiCategoryHandler by Andrii (@imitator) on CodePen.

    • Make reexports (middlewares\joiHandlersWithSchemas\index.js ) if you mind
      const joiCategoryHandler = require('./joiCategoryHandler');
      module.exports = {
      joiCategoryHandler,
      };
    • Create middleware middlewares\validateSchemaMiddleware.js

      See the Pen 35__validateSchemaMiddleware by Andrii (@imitator) on CodePen.

    • Make reexport in middlewares\index.js
      const validateSchemaMiddleware = require('./validateSchemaMiddleware');
      module.exports = {
      validateSchemaMiddleware,
      };
    • Use this middleware in routes

      See the Pen 36__use validateSchemaMiddleware in routes by Andrii (@imitator) on CodePen.