UNPKG

1.25 kBJavaScriptView Raw
1
2/**
3 * Module dependencies.
4 */
5
6var raw = require('raw-body');
7var inflate = require('inflation');
8var qs = require('qs');
9
10/**
11 * Return a Promise which parses x-www-form-urlencoded requests.
12 *
13 * Pass a node request or an object with `.req`,
14 * such as a koa Context.
15 *
16 * @param {Request} req
17 * @param {Options} [opts]
18 * @return {Function}
19 * @api public
20 */
21
22module.exports = function(req, opts){
23 req = req.req || req;
24 opts = opts || {};
25 var queryString = opts.queryString || {};
26
27 // keep compatibility with qs@4
28 if (queryString.allowDots === undefined) queryString.allowDots = true;
29
30 // defaults
31 var len = req.headers['content-length'];
32 var encoding = req.headers['content-encoding'] || 'identity';
33 if (len && encoding === 'identity') opts.length = ~~len;
34 opts.encoding = opts.encoding || 'utf8';
35 opts.limit = opts.limit || '56kb';
36 opts.qs = opts.qs || qs;
37
38 // raw-body returns a Promise when no callback is specified
39 return Promise.resolve()
40 .then(function() {
41 return raw(inflate(req), opts);
42 })
43 .then(function(str){
44 try {
45 return opts.qs.parse(str, queryString);
46 } catch (err) {
47 err.status = 400;
48 err.body = str;
49 throw err;
50 }
51 });
52};