Thinking about the correct way, how to make use of middlewares in a node.js web project using express and connect which is growing up at the moment.
Of course there are middlewares right now wich has to pass or extend requests globally but in a lot of cases there are special jobs like prepare incoming data and in this case the middleware would only work for a set of http-methods and routes.
I've a component based architecture and each component brings it's own middleware layer which can implement those for requests this component can handle. On app startup any required component is loaded and prepared. Is it a good idea to bind the middleware code execution to URLs to keep cpu load lower or is it better to use middlewares only for global purposes?
Here's some dummy how an url related middleware look like.
app.use(function(req, res, next) {
// Check if requested route is a part of the current component
// or if the middleware should be passed on any request
if (APP.controller.groups.Component.isExpectedRoute(req) ||
APP.controller.groups.Component.getConfig().MIDDLEWARE_PASS_ALL === true) {
// Execute the midleware code here
console.log('This is a route which should be afected by middleware');
...
next();
}else{
next();
}
});
It depends on your setup, but you can be creative.
Say that you want to run a certain middleware for GET
requests with a /foo
prefix. In that case, you can limit the number of calls to that middleware using something like this:
// matches '/foo', '/foo/bar', '/foo/bar/blah', ...
app.get('/foo*', YourMiddleware);
(replace app.get
with app.all
to pass all request methods through the middleware, etc.)
If you want to run the middleware only a limited number (one or two) specific routes, you can inject it in the route declaration:
app.get('/bar', YourMiddleware, function(req, res) {
...
});
If you have specific sets of middlewares, you can create arrays of them which you can use similarly:
var MiddlewareSet = [ MiddlewareA, MiddlewareB, MiddlewareC ];
...
app.get('/', MiddlewareSet, function(req, res) {
...
});