forked from nightwatchjs/nightwatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpclient.js
114 lines (96 loc) · 2.91 KB
/
httpclient.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const HttpRequest = require('../../http/request.js');
module.exports = function(settings, HttpResponse) {
// TODO: handle agent and proxy arguments below
const url = require('url');
return class HttpClient {
constructor(serverUrl, opt_agent, opt_proxy) {
this.agent_ = opt_agent || null;
// eslint-disable-next-line
const options = url.parse(serverUrl);
if (!options.hostname) {
throw new Error('Invalid URL: ' + serverUrl);
}
this.proxyOptions_ = opt_proxy ? {} : null;
const {hostname: host, pathname: path, protocol} = options;
const {log_screenshot_data} = settings;
let {port} = options;
if (port) {
port = Number(port);
HttpRequest.updateGlobalSettings({port});
} else {
port = protocol === 'https' ? 443 : 80;
}
this.options = {
host,
port,
path,
addtOpts: {
suppressBase64Data: !log_screenshot_data
},
use_ssl: protocol === 'https:'
};
this.errorTimeoutId = null;
}
isDataRedacted(data) {
for (const value of Object.values(data)) {
if (typeof(value) === 'string' && value.includes('\uE000')) {
return true;
}
}
return false;
}
/** @override */
send(httpRequest) {
const {method, data, path} = httpRequest;
const headers = {};
if (httpRequest.headers) {
httpRequest.headers.forEach(function (value, name) {
headers[name] = value;
});
}
this.options.headers = headers;
this.options.data = data;
this.options.path = path;
this.options.method = method;
this.options.redact = this.isDataRedacted(data);
const request = new HttpRequest(this.options);
return new Promise((resolve, reject) => {
request.once('success', (data, response, isRedirect) => {
const {statusCode, headers} = response;
let body = '';
if (data) {
try {
body = JSON.stringify(data);
} catch (err) {
//
}
}
if (data && data.error) {
reject(data);
} else {
const resp = new HttpResponse(statusCode, headers, body);
resolve(resp);
}
});
request.on('error', (err) => {
let {message, code} = err;
// for connection reset errors, sometimes the error event gets fired multiple times
if (this.errorTimeoutId) {
clearTimeout(this.errorTimeoutId);
}
this.errorTimeoutId = setTimeout(() => {
if (code) {
message = code + ' ' + message;
}
const error = new Error(message);
if (code) {
error.code = code;
}
reject(error);
}, 15);
});
request.send();
});
}
};
};