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.
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
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