Home > Net >  Same route, different query but different middlewares
Same route, different query but different middlewares

Time:01-05

I'm working on an API that has routes like this (all POST requests)

/friends?d=onlineFriends /friends?d=offlineFriends and on...

and this is how it's handled:

server.js

app.post("/friends", (req, res, next) => {
  let d = req.query.d
  let path "./funcs/"   d   ".js"
  return require(path)(req, res, next)
})

./funcs/onlineFriends.js

module.exports = (req, res, next) => {
  return res.sendStatus(200)
}

But the thing is, I want to use different middlewares per func, with the code above if I wanted to use a middleware it would apply to all funcs because you'd have to put it in app.post part.

I've tried following:

module.exports = (req, res, next) => {
  middleware(req, res, next)
  return res.sendStatus(200)
}

but of course it results in Cannot set headers after they are sent to the client.

I know you might ask "Why not use a router like /friends/online", I really can't change the client and this is how I must do it.

CodePudding user response:

If you have middlewares a, b and c, you can dynamically choose a combination of them and use that to handle the request:

app.post("/friends", function(req, res, next) {
  var middleware;
  switch (req.query.d) {
    case "a": middleware = [a, c]; break;
    case "b": middleware = [b]; break;
    default: return next();
  }
  express.Router().use(middleware)(req, res, next);
});
  • Related