raspberryGPIOhtmlserver/node_modules/connect/lib/middleware/json.js
node_modules/connect/lib/middleware/json.jsRaw
1
2/*!
3 * Connect - json
4 * Copyright(c) 2010 Sencha Inc.
5 * Copyright(c) 2011 TJ Holowaychuk
6 * MIT Licensed
7 */
8
9/**
10 * Module dependencies.
11 */
12
13var utils = require('../utils')
14 , _limit = require('./limit');
15
16/**
17 * noop middleware.
18 */
19
20function noop(req, res, next) {
21 next();
22}
23
24/**
25 * JSON:
26 *
27 * Parse JSON request bodies, providing the
28 * parsed object as `req.body`.
29 *
30 * Options:
31 *
32 * - `strict` when `false` anything `JSON.parse()` accepts will be parsed
33 * - `reviver` used as the second "reviver" argument for JSON.parse
34 * - `limit` byte limit disabled by default
35 *
36 * @param {Object} options
37 * @return {Function}
38 * @api public
39 */
40
41exports = module.exports = function(options){
42 var options = options || {}
43 , strict = options.strict !== false;
44
45 var limit = options.limit
46 ? _limit(options.limit)
47 : noop;
48
49 return function json(req, res, next) {
50 if (req._body) return next();
51 req.body = req.body || {};
52
53 if (!utils.hasBody(req)) return next();
54
55 // check Content-Type
56 if ('application/json' != utils.mime(req)) return next();
57
58 // flag as parsed
59 req._body = true;
60
61 // parse
62 limit(req, res, function(err){
63 if (err) return next(err);
64 var buf = '';
65 req.setEncoding('utf8');
66 req.on('data', function(chunk){ buf += chunk });
67 req.on('end', function(){
68 var first = buf.trim()[0];
69
70 if (0 == buf.length) {
71 return next(utils.error(400, 'invalid json, empty body'));
72 }
73
74 if (strict && '{' != first && '[' != first) return next(utils.error(400, 'invalid json'));
75 try {
76 req.body = JSON.parse(buf, options.reviver);
77 } catch (err){
78 err.body = buf;
79 err.status = 400;
80 return next(err);
81 }
82 next();
83 });
84 });
85 };
86};