Search code examples
node.jsexpressexpress-router

How to call router level middleware conditionally?


I have two functions to validate the request body, validation1 and validation2. Now my task is, after parsing the incoming request body, I need to validate the data with validation1 if the user role is premium user, otherwise I will validate the data using validation2.

I have tried to solve it like the following but to no avail. For some reason, the validation middlewares are not getting called.

const express = require('express');
const router = express.Router();
   
const { userController } = require('./controllers');

router.route('/check').post(
  (req, res, next) => {
    if (req.role === 'premium user') {
      validation1(someInformation);
    } else {
      validation2(someInformation);
    }
    next();
  },
  userController.check
);


const validation1 = (someInformation) => (req, res, next) => {
  // codes
  return next();
}

const validation2 = (someInformation) => (req, res, next) => {
  // codes
  return next();
}

Any help would be appreciated. Thanks in advance.


Solution

  • You should pass callback function next to validate function.

    Also change your validation function like below code:

    const express = require('express');
    const router = express.Router();
       
    const { userController } = require('./controllers');
    
    router.route('/check').post(
      (req, res, next) => {
        if (req.role === 'premium user') {
          validation1(req, res, next);
        } else {
          validation2(req, res, next);
        }
      },
      userController.check
    );
    
    
    const validation1 = (req, res, next) => {
      // codes
      return next();
    }
    
    const validation2 = (req, res, next) => {
      // codes
      return next();
    }