1

I have a routes file that looks like this,

function getEmp(req,res,next,empId) {
    return(req, res, next) => {
        getEmpById(req, res, next, employerId);
    }
}

module.exports = {
   router.get('/go', getEmp('my-id'), (req, res) => {
   res.render('view.njk', { empDetails: res.local.empDetails});
});

This works as I would expect the API call is made, and the data is rendered in the view, however I don't want my middleware to be function in the routes file I want it to be standalone file, so I moved it out into it's own file,

const { getEmpById } = require("ApiFile");

const setEmp = (employerId) => {
   return (req, res, next, employerId) => {
       getEmpById(employerId);
   }
}

module.exports = setEmp

When I pull the above into my routes file and use it as middleware then the middleware doesnt even get called?

With the middleware function in a seperate file, my routes looks like this,

const setEmp = require("../middleware/setEmp");

module.exports = {
       router.get('/go', setEmp('my-id'), (req, res) => {
       res.render('view.njk', { empDetails: res.local.empDetails});
    });

I assume I am doing something incorrectly?

Anthony Garcia-Labiad
  • 3,531
  • 1
  • 26
  • 30
Udders
  • 6,914
  • 24
  • 102
  • 194

1 Answers1

0

Change the implementation of setEmp file as:

const { getEmpById } = require("ApiFile");

const setEmp = (employerId) => {
  return (req, res, next) => {
    getEmpById(employerId);
  }
}

module.exports = setEmp

i.e., remove employerId as fourth parameter to the returned function. You can still be able to pass employerId as argument to getEmpById function because of Closures.

Dheemanth Bhat
  • 4,269
  • 2
  • 21
  • 40