datasquirel/package-shared/functions/backend/httpRequest.js
Benjamin Toby e28cf872ea type fix
2025-01-05 09:10:33 +01:00

95 lines
2.8 KiB
JavaScript

// @ts-check
const http = require("node:http");
const https = require("node:https");
const querystring = require("querystring");
const serializeQuery = require("../../utils/serialize-query");
const _ = require("lodash");
/**
* # Generate a http Request
* @type {import("../../types").HttpRequestFunctionType}
*/
module.exports = 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();
});
};