File size: 2,326 Bytes
5f341ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright Epic Games, Inc. All Rights Reserved.
var querystring = require('querystring')
const https = require('https');
const assert = require('assert');

function cleanUrl(aUrl){
	let url = aUrl;
	if(url.startsWith("https://"))
		url = url.substring("https://".length);
	
	return url
}

function createOptions(requestType, url){
	let index = url.indexOf('/');
		
	let urlParts = url.split('/', 2)
	
	return {
		hostname: (index === -1) ? url.substring(0) : url.substring(0, index),
		port: 443,
		path: (index === -1) ? '' : url.substring(index),
		method: requestType,
		timeout: 30000,
	};
}

function makeHttpsCall(options, aCallback, aError){
	//console.log(JSON.stringify(options));
	const req = https.request(options, function(response){
		let data = '';
		
		//console.log('statusCode:', response.statusCode);
		//console.log('headers:', response.headers);
		
		// A chunk of data has been received.
		response.on('data', (chunk) => {
			data += chunk;
		});
		
		// The whole response has been received. Print out the result.
		response.on('end', () => {
			if(typeof aCallback != "undefined")
				aCallback(response, data);
		});
	});
	
	req.on('timeout', function () {
		console.log("Request timed out. " + (options.timeout / 1000) + " seconds expired");

		// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js#L27
		req.destroy();
	});
	
	req.on("error", (err) => {
		if(typeof aError != "undefined") {
			aError(err);
		} else {
			console.log("Error: " + err.message);
		}
	});
	
	return req;
}

module.exports = class HttpClient {
    get(aUrl, aCallback, aError) {
		let url = cleanUrl(aUrl);
		
		let options = createOptions('GET', url);
		
		const req = makeHttpsCall(options, aCallback, aError);
		
		req.end();
    }
	
	post(aUrl, body, aCallback, aError) {
		let url = cleanUrl(aUrl);
		
		let options = createOptions('POST', url);
		
		let postBody = querystring.stringify(body);
		
		//Add extra options for POST request type
		options.headers = {
				'Content-Type': 'application/x-www-form-urlencoded',
				'Content-Length': postBody.length
			};
		
		const req = makeHttpsCall(options, aCallback, aError);
		
		req.write(postBody);
		req.end();
    }
}