Implement Discord CnC Server into Emmelia
This commit is contained in:
68
utilities/httpRequests.js
Normal file
68
utilities/httpRequests.js
Normal file
@@ -0,0 +1,68 @@
|
||||
// Debug
|
||||
const { DebugBuilder } = require("../utilities/debugBuilder.js");
|
||||
const log = new DebugBuilder("server", "httpRequests");
|
||||
// Modules
|
||||
const http = require("http");
|
||||
|
||||
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": data
|
||||
};
|
||||
|
||||
try {
|
||||
responseObject.body = JSON.parse(responseObject.body)
|
||||
}
|
||||
catch (err) {
|
||||
}
|
||||
|
||||
log.DEBUG("Response Object: ", responseObject);
|
||||
callback(responseObject);
|
||||
})
|
||||
}).on('error', err => {
|
||||
log.ERROR('Error: ', err.message)
|
||||
// TODO need to handle if the server is down
|
||||
})
|
||||
|
||||
if (requestOptions.timeout) {
|
||||
req.setTimeout(requestOptions.timeout, () => {
|
||||
callback(false);
|
||||
});
|
||||
}
|
||||
|
||||
// Write the data to the request and send it
|
||||
req.write(data)
|
||||
req.end()
|
||||
}
|
||||
Reference in New Issue
Block a user