Skip to content

Commit

Permalink
chore: lift json regex to top of file (#1670)
Browse files Browse the repository at this point in the history
  • Loading branch information
DonutEspresso committed Jun 8, 2018
1 parent fb8b7fc commit 06f3fc8
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 11 deletions.
19 changes: 13 additions & 6 deletions lib/plugins/bodyParser.js
Expand Up @@ -10,6 +10,7 @@ var jsonParser = require('./jsonBodyParser');
var formParser = require('./formBodyParser');
var multipartParser = require('./multipartBodyParser');
var fieldedTextParser = require('./fieldedTextBodyParser.js');
var regex = require('./utils/regex');

///--- Globals

Expand Down Expand Up @@ -162,12 +163,6 @@ 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 All @@ -192,6 +187,18 @@ function bodyParser(options) {
break;
}

// if we find no matches from the direct string comparisons, perform
// more expensive regex matches. map any +json to application/json.
// theoretically these could be mapped to application/json prior to the
// switch statement, but putting it here allows us to skip the regex
// entirely unless absolutely necessary. additional types could be
// added later at some point.
if (!parser) {
if (regex.jsonContentType.test(type)) {
parser = parseJson[0];
}
}

if (parser) {
parser(req, res, next);
} else if (opts && opts.rejectUnknown) {
Expand Down
14 changes: 9 additions & 5 deletions lib/plugins/jsonBodyParser.js
Expand Up @@ -6,6 +6,7 @@ var assert = require('assert-plus');
var errors = require('restify-errors');

var bodyReader = require('./bodyReader');
var regex = require('./utils/regex');

///--- API

Expand All @@ -28,13 +29,16 @@ function jsonBodyParser(options) {
// save original body on req.rawBody and req._body
req.rawBody = req._body = req.body;

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();
}
// check for empty body first, don't pay regex tax unless necessary.
// for content type, check for exact match and any of the *+json types
if (
!req.body ||
(contentType !== 'application/json' &&
!regex.jsonContentType.test(contentType))
) {
return next();
}

var params;
Expand Down
5 changes: 5 additions & 0 deletions lib/plugins/utils/regex.js
@@ -0,0 +1,5 @@
'use strict';

module.exports = {
jsonContentType: new RegExp('^application/[a-zA-Z.]+\\+json')
};

0 comments on commit 06f3fc8

Please sign in to comment.