Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(JSON5): add JSON5 mode to parse body content #143

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ var parsers = Object.create(null)
/**
* @typedef Parsers
* @type {function}
* @property {function} json5
* @property {function} json
* @property {function} raw
* @property {function} text
Expand All @@ -37,6 +38,17 @@ var parsers = Object.create(null)
exports = module.exports = deprecate.function(bodyParser,
'bodyParser: use individual json/urlencoded middlewares')

/**
* JSON parser.
* @public
*/

Object.defineProperty(exports, 'json5', {
configurable: true,
enumerable: true,
get: createParserGetter('json5')
})

/**
* JSON parser.
* @public
Expand Down Expand Up @@ -138,6 +150,9 @@ function loadParser(parserName) {

// this uses a switch for static require analysis
switch (parserName) {
case 'json5':
parser = require('./lib/types/json5')
break
case 'json':
parser = require('./lib/types/json')
break
Expand Down
171 changes: 171 additions & 0 deletions lib/types/json5.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
/*!
* body-parser
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/

'use strict'

/**
* Module dependencies.
* @private
*/

var JSON5 = require('json5')
var bytes = require('bytes')
var contentType = require('content-type')
var createError = require('http-errors')
var debug = require('debug')('body-parser:json')
var read = require('../read')
var typeis = require('type-is')

/**
* Module exports.
*/

module.exports = json

/**
* RegExp to match the first non-space in a string.
*
* Allowed whitespace is defined in RFC 7159:
*
* ws = *(
* %x20 / ; Space
* %x09 / ; Horizontal tab
* %x0A / ; Line feed or New line
* %x0D ) ; Carriage return
*/

var firstcharRegExp = /^[\x20\x09\x0a\x0d]*(.)/

/**
* Create a middleware to parse JSON bodies.
*
* @param {object} [options]
* @return {function}
* @public
*/

function json(options) {
var opts = options || {}

var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var inflate = opts.inflate !== false
var reviver = opts.reviver
var strict = opts.strict !== false
var type = opts.type || 'application/json'
var verify = opts.verify || false

if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}

// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type

function parse(body) {
if (body.length === 0) {
// special-case empty json body, as it's a common client-side mistake
// TODO: maybe make this configurable or part of "strict" option
return {}
}

if (strict) {
var first = firstchar(body)

if (first !== '{' && first !== '[') {
debug('strict violation')
throw new SyntaxError('Unexpected token ' + first)
}
}

debug('parse json')
return JSON5.parse(body, reviver)
}

return function jsonParser(req, res, next) {
if (req._body) {
return debug('body already parsed'), next()
}

req.body = req.body || {}

// skip requests without bodies
if (!typeis.hasBody(req)) {
return debug('skip empty body'), next()
}

debug('content-type %j', req.headers['content-type'])

// determine if request should be parsed
if (!shouldParse(req)) {
return debug('skip parsing'), next()
}

// assert charset per RFC 7159 sec 8.1
var charset = getCharset(req) || 'utf-8'
if (charset.substr(0, 4) !== 'utf-') {
debug('invalid charset')
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
charset: charset
}))
return
}

// read
read(req, res, next, parse, debug, {
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
}

/**
* Get the first non-whitespace character in a string.
*
* @param {string} str
* @return {function}
* @api public
*/


function firstchar(str) {
var match = firstcharRegExp.exec(str)
return match ? match[1] : ''
}

/**
* Get the charset of a request.
*
* @param {object} req
* @api private
*/

function getCharset(req) {
try {
return contentType.parse(req).parameters.charset.toLowerCase()
} catch (e) {
return undefined
}
}

/**
* Get the simple type checker.
*
* @param {string} type
* @return {function}
*/

function typeChecker(type) {
return function checkType(req) {
return Boolean(typeis(req, type))
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"depd": "~1.1.0",
"http-errors": "~1.3.1",
"iconv-lite": "0.4.12",
"json5": "^0.4.0",
"on-finished": "~2.3.0",
"qs": "5.1.0",
"raw-body": "~2.1.4",
Expand Down
Loading