This repository was archived by the owner on Nov 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathhttps_bot.js
More file actions
90 lines (76 loc) · 2.27 KB
/
https_bot.js
File metadata and controls
90 lines (76 loc) · 2.27 KB
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
// simple (and limited) wrapper to handle https requests that deal with json data
'use strict';
const HTTPS = require('https');
const HTTP = require('http');
function _SimpleRequest (method, host, port, path, data, options, callback) {
options = Object.assign({}, options || {}, { method, host, port, path });
if (!options.noJsonInRequest) {
options.headers = Object.assign({}, options.headers || {}, {
'Content-Type': 'application/json'
});
}
const protocol = options.useHttp ? HTTP : HTTPS;
let request = protocol.request(
options,
(response) => {
let responseData = '';
response.on('data', (data) => {
responseData += data;
});
response.on('end', () => {
let parsed;
if (!options.noJsonInResponse) {
try {
parsed = JSON.parse(responseData);
}
catch(error) {
return callback(`error parsing JSON data (status=${response.statusCode}): ${error} :: ${responseData.substring(0, 1000)}...`);
}
}
else {
parsed = responseData;
}
if (response.statusCode < 200 || response.statusCode >= 300) {
if (options.expectRedirect && response.statusCode >= 300 && response.statusCode < 400) {
return callback(null, response.headers.location, response);
}
else {
return callback(`error response, status code was ${response.statusCode}: ${JSON.stringify(parsed)}`, parsed, response);
}
}
else {
return callback(null, parsed, response);
}
});
response.on('error', (error) => {
return callback(`https error: ${error}`);
});
}
);
request.on('error', (error) => {
callback(error);
});
if (data) {
if (options.noJsonInRequest) {
request.write(data);
}
else {
request.write(JSON.stringify(data));
}
}
request.end();
}
module.exports = {
get: (host, port, path, data, options, callback) => {
_SimpleRequest('get', host, port, path, data, options, callback);
},
post: (host, port, path, data, options, callback) => {
_SimpleRequest('post', host, port, path, data, options, callback);
},
put: (host, port, path, data, options, callback) => {
_SimpleRequest('put', host, port, path, data, options, callback);
},
delete: (host, port, path, data, options, callback) => {
_SimpleRequest('delete', host, port, path, data, options, callback);
}
};