Skip to content

Commit

Permalink
lib/request-browser: better usage of the fetch api.
Browse files Browse the repository at this point in the history
  • Loading branch information
chjj committed Dec 16, 2023
1 parent 64b1447 commit 8325408
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions lib/request-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ class RequestOptions {
this.port = 80;
this.path = '/';
this.query = '';
this.agent = 'brq';
this.pool = false;
this.agent = null;
this.lookup = null;

this.type = null;
Expand Down Expand Up @@ -102,6 +103,11 @@ class RequestOptions {
this.password = options.password;
}

if (options.pool != null) {
assert(typeof options.pool === 'boolean');
this.pool = options.pool;
}

if (options.agent != null) {
assert(typeof options.agent === 'string');
this.agent = options.agent;
Expand Down Expand Up @@ -249,24 +255,33 @@ class RequestOptions {
getHeaders() {
const headers = new FetchHeaders();

headers.append('User-Agent', this.agent);
let referrer = 'no-referrer';

// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
if (this.agent != null)
headers.append('User-Agent', this.agent);

if (this.type)
headers.append('Content-Type', mime.type(this.type));

if (this.body)
headers.append('Content-Length', this.body.length.toString(10));

if (this.username || this.password) {
const auth = `${this.username}:${this.password}`;
const data = Buffer.from(auth, 'utf8');
headers.append('Authorization', `Basic ${data.toString('base64')}`);
}

for (const name of Object.keys(this.headers))
for (const name of Object.keys(this.headers)) {
switch (name.toLowerCase()) {
case 'referer':
case 'referrer':
referrer = this.headers[name];
continue;
}

headers.append(name, this.headers[name]);
}

return headers;
return [headers, referrer];
}

toURL() {
Expand All @@ -292,19 +307,26 @@ class RequestOptions {
}

toHTTP() {
// https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#parameters
// https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
// https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
const auth = this.username || this.password;
const [headers, referrer] = this.getHeaders();

return {
method: this.method,
headers: this.getHeaders(),
headers,
body: this.body
? new Uint8Array(this.body.buffer,
this.body.byteOffset,
this.body.byteLength)
: null,
mode: 'cors',
credentials: 'include',
cache: 'no-cache',
credentials: auth ? 'include' : 'same-origin',
cache: 'no-store',
redirect: 'follow',
referrer: 'no-referrer'
referrer,
keepalive: this.pool
};
}
}
Expand Down

0 comments on commit 8325408

Please sign in to comment.