This repository has been archived by the owner on Sep 14, 2022. It is now read-only.
Add in middleware support for swagger-node-express #153
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.