forked from lsongdev/kelp-body
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (47 loc) · 1.32 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
'use strict';
const url = require('url');
const qs = require('querystring');
const MIME = require('mime2');
const readStream = stream => new Promise((resolve, reject) => {
const buffer = [];
stream
.on('error', reject)
.on('data', chunk => buffer.push(chunk))
.on('end', () => resolve(Buffer.concat(buffer)))
});
/**
* [function description]
* @param {[type]} req [description]
* @param {[type]} res [description]
* @param {Function} next [description]
* @return {[type]} [description]
*/
module.exports = async (req, res, next) => {
const { pathname, query } = url.parse(req.url, true);
req.query = query;
req.path = pathname;
req.get = name => {
if (!name) return;
const key = name.toLowerCase();
return req.headers[key];
};
req.data = await readStream(req);
const contentType = req.get('Content-Type');
const type = (contentType || '').split(';')[0];
switch (type) {
case 'text/plain':
req.text = req.data.toString();
break;
case 'multipart/form-data':
req.body = MIME.parse(req.data, contentType);
break;
case 'application/x-www-form-urlencoded':
req.body = qs.parse(req.data + '');
break;
case 'application/json':
case 'application/csp-report':
req.body = JSON.parse(req.data);
break;
}
return next();
};