// Debug const { DebugBuilder } = require("../utilities/debugBuilder.js"); const log = new DebugBuilder("client", "httpRequests"); // Config require('dotenv').config(); // Modules const http = require("http"); exports.requestOptions = class requestOptions { constructor(path, method, hostname = undefined, headers = undefined, port = undefined) { if (method === "POST"){ this.hostname = hostname ?? process.env.SERVER_HOSTNAME ?? process.env.SERVER_IP; 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) => { if (res.statusCode >= 200 && res.statusCode <= 299) { const responseObject = { "statusCode": res.statusCode, "body": JSON.parse(data) }; log.DEBUG("Response Object: ", responseObject); callback(responseObject); } if (res.statusCode >= 300) { const responseObject = { "statusCode": res.statusCode, "body": data }; log.DEBUG("Response Object: ", responseObject); callback(responseObject); } }) }).on('error', err => { log.ERROR('Error: ', err.message) // 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; } }