Skip to content

Commit

Permalink
feat: jsonBodyParser handles extended content types *+json (#1663)
Browse files Browse the repository at this point in the history
  • Loading branch information
ifiok authored and DonutEspresso committed May 27, 2018
1 parent de72f49 commit 4537514
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 2 deletions.
6 changes: 6 additions & 0 deletions lib/plugins/bodyParser.js
Expand Up @@ -162,6 +162,12 @@ function bodyParser(options) {
var parser;
var type = req.contentType().toLowerCase();

var jsonPatternMatcher = new RegExp('^application/[a-zA-Z.]+\\+json');
// map any +json to application/json
if (jsonPatternMatcher.test(type)) {
type = 'application/json';
}

switch (type) {
case 'application/json':
parser = parseJson[0];
Expand Down
9 changes: 7 additions & 2 deletions lib/plugins/jsonBodyParser.js
Expand Up @@ -28,8 +28,13 @@ function jsonBodyParser(options) {
// save original body on req.rawBody and req._body
req.rawBody = req._body = req.body;

if (req.getContentType() !== 'application/json' || !req.body) {
return next();
var jsonPatternMatcher = new RegExp('^application/[a-zA-Z.]+\\+json');
var contentType = req.getContentType();

if (contentType !== 'application/json' || !req.body) {
if (!jsonPatternMatcher.test(contentType)) {
return next();
}
}

var params;
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -32,6 +32,7 @@
"Falco Nogatz",
"Gergely Nemeth",
"Guillaume Chauvet",
"Ifiok Idiang",
"Isaac Schlueter",
"Jacob Quatier",
"James O'Cull",
Expand Down
29 changes: 29 additions & 0 deletions test/plugins/jsonBodyParser.test.js
Expand Up @@ -489,4 +489,33 @@ describe('JSON body parser', function() {
client.write('{"malformedJsonWithPercentSign":30%}');
client.end();
});

it('should handle application/*+json as application/json', function(done) {
SERVER.use(restify.plugins.bodyParser({ maxBodySize: 1024 }));

SERVER.post('/', function(req, res, next) {
res.send(200, { length: req.body.length });
next();
});

var opts = {
hostname: '127.0.0.1',
port: PORT,
path: '/',
method: 'POST',
agent: false,
headers: {
accept: 'application/json',
'content-type': 'application/hal+json',
'transfer-encoding': 'chunked'
}
};
var client = http.request(opts, function(res) {
assert.equal(res.statusCode, 413);
res.once('end', done);
res.resume();
});
client.write('{"a":[' + new Array(512).join('1,') + '0]}');
client.end();
});
});

0 comments on commit 4537514

Please sign in to comment.