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

107 lines
3.1 KiB
JavaScript
Raw Normal View History

2025-01-05 07:46:21 +00:00
// @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";
/**
* @typedef {object} HttpRequestExtraParams
* @property {"http" | "https"} [scheme]
* @property {Object<string, any>} [body]
* @property {Object<string, any>} [query]
* @property {boolean} [urlEncodedFormBody]
*/
/**
* # Generate a http Request
* @param {import("node:https").RequestOptions & HttpRequestExtraParams} params
*
* @returns { Promise<Object<string, any> | string | null> }
*/
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;