This repository has been archived by the owner on Nov 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.js
62 lines (57 loc) · 1.96 KB
/
http.js
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
'use strict';
let logger = require('./log')();
module.exports = function () {
let index = 0;
return {
get: function (url, options) {
options = options || {};
options.method = 'GET';
return this.request(url, options);
},
request: function (url, options, data) {
let localIndex = index++;
options = options || {};
url = require('url').parse(url);
let request = {
protocol: url.protocol,
port: url.port || (url.protocol.startsWith('https') ? "443" : "80"),
hostname: url.hostname,
method: options.method || 'GET',
headers: options.headers || {},
path: url.path
};
logger.log('HTTP REQUEST [' + localIndex + '] ' + JSON.stringify(request));
if (data) {
logger.log('HTTP REQUEST DATA [' + localIndex + '] ' + data);
}
return new Promise((resolve, reject) => {
const tls = request.protocol.startsWith('https');
const lib = tls ? require('https') : require('http');
if (tls) {
request.rejectUnauthorized = require('./util')().boolean(process.env.VAMP_TLS_CHECK || true);
if (request.rejectUnauthorized && process.env.VAMP_CA) {
request.ca = require('fs').readFileSync(process.env.VAMP_CA);
}
}
const req = lib.request(request, (response) => {
const body = [];
response.on('data', (chunk) => body.push(chunk));
response.on('end', () => {
let rspBody = body.join('');
logger.log('HTTP RESPONSE [' + localIndex + '] ' + response.statusCode);
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('[' + response.statusCode + ']: ' + rspBody));
} else {
resolve(rspBody)
}
});
});
req.on('error', (err) => reject(err));
if (data) {
req.write(data);
}
req.end();
})
}
};
};