Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping and Managing node.js Middleware

If I've made some middleware that works together, what's the best convention for grouping and managing the functionality?

In my server.js file, I've currently just got them listed one after another with app.use calls.

It's occurred to me however that if the first one in my set doesn't produce any data, the subsequent ones in the group are fine to skip. I guess this is ultimately an aggregation although I haven't seen any examples of such in other projects.

like image 439
Alexander Trauzzi Avatar asked Nov 13 '22 13:11

Alexander Trauzzi


1 Answers

The connect middleware has a good example for this kind of problem. Take a look at the bodyParser:

app.use(connect.bodyParser());  // use your own grouping here

is equivalent to

app.use(connect.json());
app.use(connect.urlencoded());
app.use(connect.multipart());

Internally the bodyParser function just passes the req and res objects through each of the before mentioned middleware functions

exports = module.exports = function bodyParser(options){
  var _urlencoded = urlencoded(options)
    , _multipart = multipart(options)
    , _json = json(options);

  return function bodyParser(req, res, next) {
    _json(req, res, function(err){
      if (err) return next(err);
      _urlencoded(req, res, function(err){
        if (err) return next(err);
        _multipart(req, res, next);
      });
    });
  }  
};

The full code can be found at the github repo

like image 114
zemirco Avatar answered Nov 15 '22 05:11

zemirco