[Polyfill > Request] Tweak Request
This commit is contained in:
parent
19366fa6db
commit
3ef11ae967
1 changed files with 36 additions and 33 deletions
|
@ -2,8 +2,7 @@ const https = require('https');
|
|||
const querystring = require("querystring");
|
||||
|
||||
// Generic polyfill for "request" npm package, wrapper for https
|
||||
const nodeReq = ({ method, url, headers, qs, timeout, body, stream }) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const nodeReq = ({ method, url, headers, qs, timeout, body, stream }) => new Promise((resolve, reject) => {
|
||||
const fullUrl = `${url}${qs != null ? `?${querystring.stringify(qs)}` : ''}`; // With query string
|
||||
|
||||
let req;
|
||||
|
@ -13,6 +12,7 @@ const nodeReq = ({ method, url, headers, qs, timeout, body, stream }) => {
|
|||
headers,
|
||||
timeout
|
||||
}, async (res) => {
|
||||
console.log('https response', res.statusCode);
|
||||
if (res.statusCode === 301 || res.statusCode === 302) { // Redirect, recall function
|
||||
return resolve(await nodeReq({
|
||||
url: res.headers.location,
|
||||
|
@ -31,13 +31,16 @@ const nodeReq = ({ method, url, headers, qs, timeout, body, stream }) => {
|
|||
return resolve(e);
|
||||
}
|
||||
|
||||
console.log('https req');
|
||||
|
||||
req.on('error', resolve);
|
||||
|
||||
if (body) req.write(body); // Write POST body if included
|
||||
|
||||
req.end();
|
||||
|
||||
console.log('https ended');
|
||||
});
|
||||
};
|
||||
|
||||
const request = (...args) => { // Main function
|
||||
// We have to use ...args because fun fact! request supports both:
|
||||
|
@ -78,6 +81,7 @@ const request = (...args) => { // Main function
|
|||
const isError = !res.statusCode;
|
||||
|
||||
if (isError) {
|
||||
console.log('[OpenAsar Request Polyfill] Error:', res);
|
||||
listeners['error']?.(res);
|
||||
callback?.(res, null, null); // Return null for others?
|
||||
|
||||
|
@ -108,7 +112,6 @@ const request = (...args) => { // Main function
|
|||
return ret;
|
||||
};
|
||||
|
||||
['get']
|
||||
// Method functions
|
||||
request.get = (url, callback) => request({ url: url, method: 'GET' }, callback);
|
||||
request.post = (url, callback) => request({ url: url, method: 'POST' }, callback);
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue