Reputation: 331
I am working on a backend of web application. And I have made a bunch of middlewares to be executed for each request that comes in -- [logging(before), authentication, Etag(Before), Nonce, httpRequest, Etag(after), logging(after)]. Now my problem is that, while processing each request, there are some special cases happen when the request should skip the rest of the middleware and just do logging. I can do it the dump way just make all the middleware to check if certain condition has happened and if true just call next()
, and otherwise process the request using the middleware. But I am wondering if there is a clever way to do this?
Here is the snippet of the code I am currently using to configure the order of the middleware to be executed:
async.series(operations, function(err) {
if(err) {
console.log('Something blew up!!!!!!');
return next(err);
}
console.log('middleware get executed');
// no errors so pass control back to express
next();
});
Where the "operations" variable is the list of middlewares I need to execute in order. I need to use the async.series() since I need to make the order the middleware configurable. Is there a clever I can keep the order of middlewares configurable and fulfill my request as I said above?
EDIT:
An example where I need to skip the rest of the middleware is when authentication fails and write the statusCode to be "401 unauthorized", then for the stack of the middleware [logging(before), authentication, Etag(Before), Nonce, httpRequest, Etag(after), logging(after)], I will jump from authentication to logging(after). and then that would be the end of the request.
Upvotes: 0
Views: 255
Reputation: 2083
I had tried to understand your's concern
I am giving a snippet to execute middle ware function in row on the basis of need.
async.each(operations, function(operation, callback) {
if(operation) {
// if operation is required execute here
callback();
} else {
// otherwise skip just to call callback() here
callback();
}
}, function(err){
if( err ) {
console.log(err);
} else {
next();
}
});
all the operations in an array and to execute all one by one async provides .each.
Its not mandatory to call each operation. You just skip by call callback() in else condition. I want to say that in if clause you can put your mandatory execution condition.
Thanks
Upvotes: 1