forked from oraoto/pib
-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathbreakoutRequest.js
55 lines (48 loc) · 1.28 KB
/
breakoutRequest.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
export const breakoutRequest = request => {
let getPost = Promise.resolve('');
if(request.body)
{
getPost = new Promise(accept => {
const reader = request.body.getReader();
const postBody = [];
const processBody = ({done, value}) => {
if(value)
{
postBody.push([...value].map(x => String.fromCharCode(x)).join(''));
}
if(!done)
{
return reader.read().then(processBody);
}
accept(postBody.join(''));
};
return reader.read().then(processBody);
});
}
else if(request.arrayBuffer)
{
getPost = request.arrayBuffer().then(
buffer => [...new Uint8Array(buffer)].map(x => String.fromCharCode(x)).join('')
);
}
else if(request.on)
{
getPost = new Promise(accept => {
let body = [];
request.on('data', chunk => body.push(chunk));
request.on('end', () => accept(
[...new Uint8Array(Buffer.concat(body))].map(x => String.fromCharCode(x)).join(''))
);
});
}
const url = new URL(request.url);
return getPost.then(post => ({
url
, method: request.method
, get: url.search ? url.search.substr(1) : ''
, post: request.method === 'POST' ? post : null
, contentType: request.method === 'POST'
? (request.headers && (request.headers.get('Content-Type')) || 'application/x-www-form-urlencoded')
: null
}));
};