forked from macedigital/express-xml-bodyparser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (54 loc) · 1.61 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Connect/Express compatible middleware for parsing raw xml body
*
* @license MIT
*/
var parseString = require('xml2js').parseString,
// inlined from connect's 'utils.js' file
utils = {
hasBody: function (req) {
var encoding = 'transfer-encoding' in req.headers,
length = 'content-length' in req.headers && req.headers['content-length'] !== '0';
return encoding || length;
},
mime: function (req) {
var str = req.headers['content-type'] || '';
return str.split(';')[0];
}
};
module.exports = function (opts) {
var options = opts || {
async: true,
explicitArray: true,
normalize: true,
normalizeTags: true,
trim: true
};
return function xmlbodyparser(req, res, next) {
var data = '';
if (req._body) {
return next();
}
req.body = req.body || {};
if (!utils.hasBody(req) || !exports.regexp.test(utils.mime(req))) {
return next();
}
req._body = true;
req.setEncoding('utf-8');
req.on('data', function (chunk) {
data += chunk;
});
req.on('end', function () {
parseString(data, options, function (err, json) {
if (err) {
err.status = 400;
return next(err);
}
req.body = json;
req.rawBody = data;
next();
});
});
};
};
exports.regexp = /^(text\/xml|application\/([\w!#\$%&\*`\-\.\^~]+\+)?xml)$/i;