Initial commit
[yaffs-website] / node_modules / body-parser / lib / types / json.js
1 /*!
2  * body-parser
3  * Copyright(c) 2014 Jonathan Ong
4  * Copyright(c) 2014-2015 Douglas Christopher Wilson
5  * MIT Licensed
6  */
7
8 'use strict'
9
10 /**
11  * Module dependencies.
12  * @private
13  */
14
15 var bytes = require('bytes')
16 var contentType = require('content-type')
17 var createError = require('http-errors')
18 var debug = require('debug')('body-parser:json')
19 var read = require('../read')
20 var typeis = require('type-is')
21
22 /**
23  * Module exports.
24  */
25
26 module.exports = json
27
28 /**
29  * RegExp to match the first non-space in a string.
30  *
31  * Allowed whitespace is defined in RFC 7159:
32  *
33  *    ws = *(
34  *            %x20 /              ; Space
35  *            %x09 /              ; Horizontal tab
36  *            %x0A /              ; Line feed or New line
37  *            %x0D )              ; Carriage return
38  */
39
40 var firstcharRegExp = /^[\x20\x09\x0a\x0d]*(.)/
41
42 /**
43  * Create a middleware to parse JSON bodies.
44  *
45  * @param {object} [options]
46  * @return {function}
47  * @public
48  */
49
50 function json(options) {
51   var opts = options || {}
52
53   var limit = typeof opts.limit !== 'number'
54     ? bytes.parse(opts.limit || '100kb')
55     : opts.limit
56   var inflate = opts.inflate !== false
57   var reviver = opts.reviver
58   var strict = opts.strict !== false
59   var type = opts.type || 'application/json'
60   var verify = opts.verify || false
61
62   if (verify !== false && typeof verify !== 'function') {
63     throw new TypeError('option verify must be function')
64   }
65
66   // create the appropriate type checking function
67   var shouldParse = typeof type !== 'function'
68     ? typeChecker(type)
69     : type
70
71   function parse(body) {
72     if (body.length === 0) {
73       // special-case empty json body, as it's a common client-side mistake
74       // TODO: maybe make this configurable or part of "strict" option
75       return {}
76     }
77
78     if (strict) {
79       var first = firstchar(body)
80
81       if (first !== '{' && first !== '[') {
82         debug('strict violation')
83         throw new SyntaxError('Unexpected token ' + first)
84       }
85     }
86
87     debug('parse json')
88     return JSON.parse(body, reviver)
89   }
90
91   return function jsonParser(req, res, next) {
92     if (req._body) {
93       return debug('body already parsed'), next()
94     }
95
96     req.body = req.body || {}
97
98     // skip requests without bodies
99     if (!typeis.hasBody(req)) {
100       return debug('skip empty body'), next()
101     }
102
103     debug('content-type %j', req.headers['content-type'])
104
105     // determine if request should be parsed
106     if (!shouldParse(req)) {
107       return debug('skip parsing'), next()
108     }
109
110     // assert charset per RFC 7159 sec 8.1
111     var charset = getCharset(req) || 'utf-8'
112     if (charset.substr(0, 4) !== 'utf-') {
113       debug('invalid charset')
114       next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
115         charset: charset
116       }))
117       return
118     }
119
120     // read
121     read(req, res, next, parse, debug, {
122       encoding: charset,
123       inflate: inflate,
124       limit: limit,
125       verify: verify
126     })
127   }
128 }
129
130 /**
131  * Get the first non-whitespace character in a string.
132  *
133  * @param {string} str
134  * @return {function}
135  * @api public
136  */
137
138
139 function firstchar(str) {
140   var match = firstcharRegExp.exec(str)
141   return match ? match[1] : ''
142 }
143
144 /**
145  * Get the charset of a request.
146  *
147  * @param {object} req
148  * @api private
149  */
150
151 function getCharset(req) {
152   try {
153     return contentType.parse(req).parameters.charset.toLowerCase()
154   } catch (e) {
155     return undefined
156   }
157 }
158
159 /**
160  * Get the simple type checker.
161  *
162  * @param {string} type
163  * @return {function}
164  */
165
166 function typeChecker(type) {
167   return function checkType(req) {
168     return Boolean(typeis(req, type))
169   }
170 }