-
Notifications
You must be signed in to change notification settings - Fork 1
/
uwsHelpers.js
79 lines (69 loc) · 1.98 KB
/
uwsHelpers.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const TextDecoder = new (require('util').TextDecoder)();
/**
* Decoded uWebSockets.js.HttpRequest.
* @typedef UWSDecodedRequest
* @property {string} url Called URL
* @property {string} method HTTP method (get, post, put, delete, etc.)
* @property {string} query Request's query string (part after ?)
* @property {Object.<string, string|string[]>} headers Requests headers
*/
/**
* @exports uwsHelpers/UWSDecodedRequest
*/
/**
* Decode a uWebSockets.js request into a convenient object.
*
* @private
* @param {UWSResponse} uwsResponse For whatever reason, some info can only be found in the response object.
* @param {UWSRequest} uwsRequest The request object we want to decode
* @return {UWSDecodedRequest}
*/
function decodeRequest(uwsResponse, uwsRequest){
// noinspection JSValidateTypes
/** @type {UWSDecodedRequest} */
const request = {
headers : {}
};
uwsRequest.forEach((k,v)=>{ request.headers[k] = v; });
request.url = uwsRequest.getUrl();
request.method = uwsRequest.getMethod();
request.query = uwsRequest.getQuery();
return request;
}
/**
* Write the given headers to the provided uWebSockets.js response object.
*
* @private
* @param {UWSResponse} uwsResponse
* @param {Object.<string, string|string[]>} headers
*/
function writeHeaders(uwsResponse, headers){
uwsResponse.cork(() => {
if('status' in headers){
uwsResponse.writeStatus(
typeof headers['status'] === 'string'
? headers['status']
: headers['status'].toString()
);
delete headers['status'];
}
Object.keys(headers || {}).forEach(header => {
//if(header === 'content-length') return;
if(Array.isArray(headers[header])){
headers[header].forEach(val => uwsResponse.writeHeader(
header,
typeof val === 'string' ? val : val.toString()
));
} else uwsResponse.writeHeader(
header,
typeof headers[header] === 'string'
? headers[header]
: headers[header].toString()
);
});
});
}
module.exports = {
writeHeaders,
decodeRequest
};