wordnik/swagger-node-express — pull request #153 by wonderlic-chrisk (2014-08-07 21:57:46+00:00)
Title: Add in middleware support for swagger-node-express

It is quite common (and built into express) to have a piece of middleware act upon a request. Swagger doesn't have this capability, but it would be relatively straightforward to add (and quite useful). So, I added in a middleware construct:

For starters, in the Swagger constructor there is a new property:

this.middleware = [];

There is also a new helper method to add middleware:

Swagger.prototype.addMiddleware = function(m) {
this.middleware.push(m);
}

And finally, the code that actually calls out to the middleware BEFORE calling into the action of method:

var success = true;
if (self.middleware.length) {
_.forEach(self.middleware, function(m) {
var ret = m(req, res, spec, self.allModels);
if (ret) {
var message = ret.message || 'An unexpected error has occurred';
var code = ret.code || 500;
res.send(JSON.stringify({
'message': message,
'code': code
}), code);
success = false;
return success;
}
});
}

if (success) {
callback(req, res, next);
}

As the middleware could literally be anything (additional validation of the request, additional error handling, adding object / properties to the req / res, etc.), I wanted to pass as much information to them as possible. As such, I chose the req and res of the request, followed by the spec of the method (so that someone could turn off a particular piece of middleware with an additional spec property, the middleware can access the spec to see the parameters or description or whatever, etc.), followed lastly by any models that are defined inside swagger.

This is similar, but implemented differently, to #87. This is all handled inside swagger, whereas #87 handles an array of actions.