-
Notifications
You must be signed in to change notification settings - Fork 5
/
http-util.js
91 lines (82 loc) · 2.63 KB
/
http-util.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
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
// Native node http/https modules wrapped with promises
let https = require('https');
let http = require('http');
// Adjustable parameters
// request timeout in seconds
const REQ_TIMEOUT = 3;
// Connection over ssl is established using the following schema
// let fs = require('fs');
//
// let options = {
// hostname: url,
// port: port,
// path: path,
// method: 'GET',
// key: fs.readFileSync('cert/key_338042844'),
// cert: fs.readFileSync('cert/cert_936367665')
// };
module.exports = class HttpUtil {
httpsGet(url, port, path, req_timeout=REQ_TIMEOUT) {
let options = {
hostname: url,
port: port,
path: path,
method: 'GET',
rejectUnauthorized: false // security issue (hacky way to parse 1317)
};
// create new promise
return new Promise((resolve, reject) => {
// request timeout
setTimeout(() => {
reject(new Error(`${new Date()} - ${req_timeout}s timeout exceeded`));
}, req_timeout*1000);
https.request(options, (res) => {
// response status check
if (res.statusCode < 200 || res.statusCode > 299) {
reject(new Error(`${new Date()} - rejection in httpsGetText with status ${res.statusCode}`));
}
// var to store res body
let res_body = "";
// get body (by chunks)
res.on('data', (data) => {
res_body += data;
});
// resolve promise(return body as text)
res.on('end', () => {
resolve(res_body);
});
}).on('error', () => {reject(new Error(`${new Date()} - request rejection in httpsGetText`))}).end();
});
}
httpGet(url, port, path, req_timeout=REQ_TIMEOUT) {
let options = {
hostname: url,
port: port,
path: path,
method: 'GET'
};
// create new promise
return new Promise((resolve, reject) => {
// request timeout
setTimeout(() => {
reject(new Error(`${new Date()} - ${req_timeout}s timeout exceeded`));
}, req_timeout*1000);
http.request(options, (res) => {
// response status check
if (res.statusCode < 200 || res.statusCode > 299) {
reject(new Error(`${new Date()} - rejection in httpGetText with status ${res.statusCode}`));
}
// var to store res body
let res_body = "";
// get body (by chunks)
res.on('data', (data) => {
res_body += data;
});
// resolve promise(return body as text)
res.on('end', () => {
resolve(res_body);
});
}).on('error', () => {reject(new Error(`${new Date()} - request rejection in httpGetText`))}).end();
});
}
}