datasquirel/package-shared/functions/backend/httpRequest.js

95 lines
2.8 KiB
JavaScript
Raw Normal View History

2025-01-05 07:46:21 +00:00
// @ts-check
2025-01-05 08:10:33 +00:00
const http = require("node:http");
const https = require("node:https");
const querystring = require("querystring");
const serializeQuery = require("../../utils/serialize-query");
const _ = require("lodash");
2025-01-05 07:46:21 +00:00
/**
* # Generate a http Request
2025-01-05 08:03:03 +00:00
* @type {import("../../types").HttpRequestFunctionType}
2025-01-05 07:46:21 +00:00
*/
2025-01-05 08:10:33 +00:00
module.exports = function httpRequest(params) {
2025-01-05 07:46:21 +00:00
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();
});
2025-01-05 08:10:33 +00:00
};