97 lines
2.8 KiB
JavaScript
97 lines
2.8 KiB
JavaScript
// @ts-check
|
|
|
|
import http from "node:http";
|
|
import https from "node:https";
|
|
import querystring from "querystring";
|
|
import serializeQuery from "../../utils/serialize-query";
|
|
import _ from "lodash";
|
|
|
|
/**
|
|
* # Generate a http Request
|
|
* @type {import("../../types").HttpRequestFunctionType}
|
|
*/
|
|
async function httpRequest(params) {
|
|
return new Promise((resolve, reject) => {
|
|
const isUrlEncodedFormBody = params.urlEncodedFormBody;
|
|
|
|
const reqPayloadString = params.body
|
|
? isUrlEncodedFormBody
|
|
? querystring.stringify(params.body)
|
|
: JSON.stringify(params.body).replace(/\n|\r|\n\r/gm, "")
|
|
: undefined;
|
|
|
|
const reqQueryString = params.query
|
|
? serializeQuery(params.query)
|
|
: undefined;
|
|
|
|
const paramScheme = params.scheme;
|
|
const finalScheme = paramScheme == "http" ? http : https;
|
|
|
|
const finalPath = params.path
|
|
? params.path + (reqQueryString ? reqQueryString : "")
|
|
: undefined;
|
|
|
|
delete params.body;
|
|
delete params.scheme;
|
|
delete params.query;
|
|
delete params.urlEncodedFormBody;
|
|
|
|
/** @type {import("node:https").RequestOptions} */
|
|
const requestOptions = {
|
|
...params,
|
|
headers: {
|
|
"Content-Type": isUrlEncodedFormBody
|
|
? "application/x-www-form-urlencoded"
|
|
: "application/json",
|
|
"Content-Length": reqPayloadString
|
|
? Buffer.from(reqPayloadString).length
|
|
: undefined,
|
|
...params.headers,
|
|
},
|
|
port: paramScheme == "https" ? 443 : params.port,
|
|
path: finalPath,
|
|
};
|
|
|
|
const httpsRequest = finalScheme.request(
|
|
requestOptions,
|
|
/**
|
|
* Callback Function
|
|
*
|
|
* @description https request callback
|
|
*/
|
|
(response) => {
|
|
var str = "";
|
|
|
|
response.on("data", function (chunk) {
|
|
str += chunk;
|
|
});
|
|
|
|
response.on("end", function () {
|
|
try {
|
|
resolve(JSON.parse(str));
|
|
} catch (/** @type {any} */ error) {
|
|
console.log("Route ERROR:", error.message);
|
|
resolve(null);
|
|
}
|
|
});
|
|
|
|
response.on("error", (err) => {
|
|
resolve(null);
|
|
});
|
|
}
|
|
);
|
|
|
|
if (reqPayloadString) {
|
|
httpsRequest.write(reqPayloadString);
|
|
}
|
|
|
|
httpsRequest.on("error", (error) => {
|
|
console.log("HTTPS request ERROR =>", error);
|
|
});
|
|
|
|
httpsRequest.end();
|
|
});
|
|
}
|
|
|
|
module.exports = httpRequest;
|