senchalabs/connect — Issue #407: make bodyParser more middlewarish
Author: icambron
Created: 2011-11-04 20:39:51+00:00
State: open

I wanted to set up bodyParser to parse POSTed XML. However, the XML library I used (xml2js) wants the caller to hand it a callback (e.g. `xml.parseString(body, fn)`) rather than returning an XML object. That doesn't quite match up with bodyParser, which needs you to do `connect.bodyParser.parse['application/xml'] = parseString`. So there's a synchronous vs asynchronous issue.

I ended up writing a piece of middleware to do this:

```javascript
var xml = require("xml2js");

module.exports = function(req, res, next){
if (req.headers['content-type'] == 'application/xml'){
var parser = new xml.Parser();
var data = '';
req.setEncoding('utf8');
req.on('data', function(chunk) { data += chunk; });
req.on('end', function(){
parser.parseString(data, function(err, result){
req.body = result;
next();
});
});
}
else{
next();
}
};
```
Works fine, but obviously that repeats a lot of code with the bodyParser, so not ideal. I'm not sure what the best solution is, but it feels like something better should be possible here.