-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
57 lines (54 loc) · 1.51 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
50
51
52
53
54
55
56
57
'use strict';
const url = require('url');
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)))
});
const decodeQuery = qs => qs.split('&').reduce((query, str) => {
const [k, v] = str.split('=');
query[decodeURIComponent(k)] = decodeURIComponent(v);
return query;
}, {});
/**
* [function description]
* @param {[type]} req [description]
* @param {[type]} res [description]
* @param {Function} next [description]
* @return {[type]} [description]
*/
module.exports = async (req, res, next) => {
try {
const o = url.parse(req.url, true);
req.query = o.query;
req.path = o.pathname;
Object.assign(req, o);
} catch (e) { };
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 = decodeQuery(req.data.toString());
break;
case 'application/json':
case 'application/csp-report':
req.body = JSON.parse(req.data);
break;
}
return next();
};