-
Notifications
You must be signed in to change notification settings - Fork 21
/
node.js
53 lines (45 loc) · 1.54 KB
/
node.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
/**
* Copyright 2013 MongoDB Inc
* Author: Henrik Ingo
*
* Note: This software is published as open source for purposes of sharing
* MongoDB examples and use cases. This is not an official product of MongoDB Inc
* and there's no support available.
*/
// Node.js entry file, contains only Node.js specific things
// why is this here?
//var clone = require('clone');
var xml2json = module.exports.xml2json = require('./xml2json.js');
var json2xml = module.exports.json2xml = require('./json2xml.js');
// Add 2 node.js middleware filters
/**
* Pull data in req.body to req.rawBody where it can be read as simple text
*
* node.js / restify is so json centric, we have to implement xml support ourselves
*/
module.exports.rawBodyParser = function( req, res, next ) {
var chunks = [];
req.on('data', function (data) {
chunks.push(data);
});
req.on('end', function(){
req.rawBody = Buffer.concat(chunks).toString();
});
return next();
};
/**
* When req.body contains application/xml, translate it to Json and put into req.params
*/
module.exports.xmlToJsonParams = function( req, res, next ) {
var jsObj = {};
if ( req.headers["content-type"] == "application/xml" ) {
jsObj = xml2json.toObj( xml2json.parseXml( req.rawBody ) );
for ( var key in jsObj ) {
// Avoid overwriting things that might already be there (using params is wrong, but this is how rest of crest works...)
if( ! req.params[key] ) {
req.params[key] = jsObj[key];
}
}
}
return next();
};