]> git.cworth.org Git - obsolete/notmuch-web/blob - node_modules/express/node_modules/connect/lib/middleware/bodyParser.js
Install the "express" node module via npm
[obsolete/notmuch-web] / node_modules / express / node_modules / connect / lib / middleware / bodyParser.js
1
2 /*!
3  * Connect - bodyParser
4  * Copyright(c) 2010 Sencha Inc.
5  * Copyright(c) 2011 TJ Holowaychuk
6  * MIT Licensed
7  */
8
9 /**
10  * Module dependencies.
11  */
12
13 var qs = require('qs');
14
15 /**
16  * Extract the mime type from the given request's
17  * _Content-Type_ header.
18  *
19  * @param  {IncomingMessage} req
20  * @return {String}
21  * @api private
22  */
23
24 function mime(req) {
25   var str = req.headers['content-type'] || '';
26   return str.split(';')[0];
27 }
28
29 /**
30  * Parse request bodies.
31  *
32  * By default _application/json_ and _application/x-www-form-urlencoded_
33  * are supported, however you may map `connect.bodyParser.parse[contentType]`
34  * to a function of your choice to replace existing parsers, or implement
35  * one for other content-types.
36  *
37  * Examples:
38  *
39  *      connect.createServer(
40  *          connect.bodyParser()
41  *        , function(req, res) {
42  *          res.end('viewing user ' + req.body.user.name);
43  *        }
44  *      );
45  *
46  * Since both _json_ and _x-www-form-urlencoded_ are supported by
47  * default, either of the following requests would result in the response
48  * of "viewing user tj".
49  *
50  *      $ curl -d 'user[name]=tj' http://localhost/
51  *      $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://localhost/
52  *
53  * @return {Function}
54  * @api public
55  */
56
57 exports = module.exports = function bodyParser(){
58   return function bodyParser(req, res, next) {
59     var parser = exports.parse[mime(req)];
60     if (parser && !req.body) {
61       var data = '';
62       req.setEncoding('utf8');
63       req.on('data', function(chunk) { data += chunk; });
64       req.on('end', function(){
65         req.rawBody = data;
66         try {
67           req.body = data
68             ? parser(data)
69             : {};
70         } catch (err) {
71           return next(err);
72         }
73         next();
74       });
75     } else {
76       next();
77     }
78   }
79 };
80
81 /**
82  * Supported decoders.
83  *
84  *  - application/x-www-form-urlencoded
85  *  - application/json
86  */
87
88 exports.parse = {
89     'application/x-www-form-urlencoded': qs.parse
90   , 'application/json': JSON.parse
91 };