-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse-body.js
57 lines (45 loc) · 1.34 KB
/
parse-body.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 http = require('http');
const querystring = require('querystring');
/**
* @function parseBody
*
* Receive a POST body and output to JSON when finished.
*
* @param {Object} req - Usual Node request object.
* @param {Number} limit - The POST body max size in bytes.
* @param {Function} callback
*
* @return {undefined}
*/
function parseBody(req, limit, callback) {
const body = [];
function handleData(data) {
body.push(data);
/**
Stop collecting data and call the callback with an error if request exceeds limit.
Calling function should close the connection.
*/
if (Buffer.concat(body).length > limit) {
req.removeListener('data', handleData);
req.removeListener('end', handleEnd);
const error = new Error();
error.httpCode = 413;
error.message = http.STATUS_CODES[413];
callback(error);
}
}
function handleEnd() {
const type = req.headers['content-type'];
if (type === 'application/x-www-form-urlencoded') {
callback(null, querystring.parse(Buffer.concat(body).toString()));
} else if (type === 'application/json') {
callback(null, JSON.parse(Buffer.concat(body).toString()));
} else {
callback(null, Buffer.concat(body).toString());
}
}
req.on('data', handleData);
req.on('end', handleEnd);
}
module.exports = parseBody;