Files
DRB-CnC/Client/utilities/httpRequests.js
2023-08-04 23:44:28 -04:00

73 lines
2.6 KiB
JavaScript

// Debug
const { DebugBuilder } = require("../utilities/debugBuilder.js");
const log = new DebugBuilder("client", "httpRequests");
// Config
require('dotenv').config();
// Modules
const http = require("http");
const { isJsonString } = require("./utilities.js");
exports.requestOptions = class requestOptions {
constructor(path, method, hostname = undefined, headers = undefined, port = undefined) {
if (["POST", "PUT"].includes(method)){
log.VERBOSE("Hostname Vars: ", hostname, process.env.SERVER_HOSTNAME, process.env.SERVER_IP);
if (hostname) this.hostname = hostname;
if (!this.hostname && process.env.SERVER_HOSTNAME) this.hostname = process.env.SERVER_HOSTNAME;
if (!this.hostname && process.env.SERVER_IP) this.hostname = process.env.SERVER_IP;
if (!this.hostname) throw new Error("No server hostname / IP was given when creating a request");
this.path = path;
this.port = port ?? process.env.SERVER_PORT;
this.method = method;
this.headers = headers ?? {
'Content-Type': 'application/json',
};
}
}
}
/**
* Send the HTTP request to the server
* @param requestOptions
* @param data
* @param callback
*/
exports.sendHttpRequest = function sendHttpRequest(requestOptions, data, callback){
log.DEBUG("Sending a request to: ", requestOptions.hostname, requestOptions.port)
// Create the request
const req = http.request(requestOptions, res => {
res.on('data', (data) => {
const responseObject = {
"statusCode": res.statusCode,
"body": (isJsonString(data.toString())) ? JSON.parse(data.toString()) : data.toString()
};
log.VERBOSE("Response Object: ", responseObject);
callback(responseObject);
})
}).on('error', err => {
if (err.code === "ECONNREFUSED"){
// Bot refused connection, assumed offline
log.WARN("Connection Refused");
}
else log.ERROR('Error: ', err.message, err);
callback(undefined);
// TODO need to handle if the server is down
})
// Write the data to the request and send it
req.write(data);
req.end();
}
exports.onHttpError = function onHttpError(httpStatusCode) {
switch(httpStatusCode){
case 404:
// Endpoint not found
log.WARN("404 received");
break;
default:
// Unhandled HTTP error code
log.ERROR("HTTP request returned with status: ", httpStatusCode)
break;
}
}