visionmedia/superagent — pull request #176 by CamShaft (2013-02-02 01:07:25+00:00)
Title: Middleware Support

I've implemented middleware support for requests and responses. This allows you to extend superagent in a really powerful way. For example, you can log all of the requests/responses:

```js
var request = require("superagent");

request
.get("http://localhost:5000")
.use(function logger(req, next){
// This will be called on the request
console.log(req.url);

next(null, function logger(res, prev){
// This will be called on the response
console.log(res.text);
prev();
});
})
.end(function(err, res){
// Handle result
});
```

It also could be used for auth:

```js
var request = require("superagent");

var authorizeRequest = function(token) {
return function authorizeRequest(req, next) {
req.set('authorization', 'Bearer '+token);
next();
}
};

request
.get("http://localhost:5000/api")
.use(authorizeRequest("this-is-a-secret"))
.end(function(err, res){
// Handle response
});
```

I've exposed the default array of middleware so you can add your own:

```js
var request = require("superagent");

request.middleware.push(function logger(req, next){
console.log(req.url);
next();
});

request
.get("http://localhost:5000/api")
.end(function(err, res){
// Handle response
});
// Logs "http://localhost:5000/api"
```

I also converted the [current response parser](https://github.com/visionmedia/superagent/blob/master/lib/node/index.js#L635) into two middleware functions ([redirect](https://github.com/CamShaft/superagent/blob/master/lib/node/middleware/redirect.js) and [bodyParser](https://github.com/CamShaft/superagent/blob/master/lib/node/middleware/bodyParser.js))

Let me know what you think :smiley: