// Debug const { DebugBuilder } = require("../utilities/debugBuilder.js"); const log = new DebugBuilder("server", "httpRequests"); // Modules const http = require("http"); const { isJsonString } = require("./utils.js"); exports.requestOptions = class requestOptions { /** * Construct an HTTP request * @param {*} method Method of request to use [GET, POST] * @param {*} headers Headers of the request, not required but will get filled with default values if not set * @param {*} hostname The destination of the request * @param {*} port The port for the destination, will use 3001 by default */ constructor(path, method, hostname, port = 3001, headers = undefined, timeout = undefined) { this.hostname = hostname; this.path = path; this.port = port; this.method = method; this.timeout = timeout; if (method === "POST"){ 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) : data.toString() }; log.DEBUG("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(); }