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 ?
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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With