Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodeJS (express,connect) - Dynamically add middleware in current flow

I am currently working on formBuilder (client javascript <=> JSON <=> node), so i need effective way to handle JSON data on server. All forms are bind on one route, catched by middleware, so i need something like this:

Code is simplified (no regexs, req validators etc ..)

var middleware = require('../middleware'); // simple dir to object export

exports = module.exports =function(req,res,next) {
  if(req.xhr && req.is('application/json')) {
    var i, items = req.body.events.length;
    for(i = 0; i < items; i++) {
      var event = req.body.events[i];
      if(middleware.forms[event] {
        // -----------------
        and here add that middleware into current flow ..
        // -----------------
      }
    }
  } else {
    return next();
}

Easiest way is to prepare list of middleware, which will be used and call them in final route witch async .. but that i donw regard this as good way ..

So, i there any way to add requested middlwares to current flow, but before filan route ?

like image 976
Michal Taneček Avatar asked Dec 26 '22 20:12

Michal Taneček


1 Answers

Middleware are just functions. So there is nothing wrong with just calling them. I had the same problem last week and I wrote a little helper.

 var walkSubstack = function (stack, req, res, next) {

  if (typeof stack === 'function') {
    stack = [stack];
  }

  var walkStack = function (i, err) {

    if (err) {
      return next(err);
    }

    if (i >= stack.length) {
      return next();
    }

    stack[i](req, res, walkStack.bind(null, i + 1));

  };

  walkStack(0);

};

You can use it with an array or just one function.

walkSubstack(middleware, req, res, next);
//or
walkSubstack([middleware, middleware], req, res, next);
like image 115
Pickels Avatar answered Dec 31 '22 08:12

Pickels