-
Notifications
You must be signed in to change notification settings - Fork 17
/
parseDataToObject.js
59 lines (55 loc) · 2.28 KB
/
parseDataToObject.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
58
59
const {STRINGS} = require('./constants');
const {BLANK, CRLF, SEPARATOR} = STRINGS;
/**
*
* @param data
* @param isResponse - Is a ResponseMessage.
* @param chunked - Is response chunked.
* @returns {Object} HTTP-Message - {method,path,version,headers:{},body}
*/
module.exports = function parseDataToObject(data, isResponse = false, chunked = false) {
//TODO make secure
const dataString = data.toString();
const splitAt = dataString.indexOf(CRLF + CRLF);
const infoObject = {};
if (!chunked) {
const [headers, body] = [dataString.slice(0, splitAt), dataString.slice(splitAt + 1)];
const headerRows = headers.split(CRLF, 50);
for (let i = 0; i < headerRows.length; i++) {
const headerRow = headerRows[i];
if (i === 0) { //first row contain method, path and type
const firstSplitIndex = headerRow.indexOf(BLANK);
const [method, pathWithVersion] = [headerRow.slice(0, firstSplitIndex), headerRow.slice(firstSplitIndex + 1)];
const secondSplitIndex = pathWithVersion.indexOf(BLANK);
const [path, version] = [pathWithVersion.slice(0, secondSplitIndex), pathWithVersion.slice(secondSplitIndex + 1)];
if (isResponse) {
infoObject.version = method;
infoObject.statusCode = path;
infoObject.statusText = version;
}
else {
infoObject.method = method;
infoObject.path = path;
infoObject.version = version;
}
}
else {
infoObject.headers = infoObject.headers || {};
const splitIndexRow = headerRow.indexOf(SEPARATOR);
const [attribute, value] = [headerRow.slice(0, splitIndexRow), headerRow.slice(splitIndexRow + 1)];
if (attribute && value) {
const lowerAttribute = attribute.trim().toLowerCase();
infoObject.headers[lowerAttribute] = value.trim();
}
}
}
if (body) {
infoObject.body = body;
}
}
else {
// data is only the chunked body
infoObject.body = dataString;
}
return infoObject;
};