-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathhttp.js
179 lines (147 loc) · 5.26 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
'use strict';
let http = require('http');
let https = require('https');
let zlib = require('zlib');
let Buffer = require('buffer').Buffer;
let version = require('../../package.json').version;
let xml2js = require('xml2js');
let exceptions = require('./exceptions');
let Util = require('./util').Util;
let wrapPrototype = require('@braintree/wrap-promise').wrapPrototype;
class Http {
constructor(config) {
this.config = config;
}
checkHttpStatus(status) {
switch (status.toString()) {
case '200':
case '201':
case '422': return null;
case '401': return exceptions.AuthenticationError('Authentication Error'); // eslint-disable-line new-cap
case '403': return exceptions.AuthorizationError('Authorization Error'); // eslint-disable-line new-cap
case '404': return exceptions.NotFoundError('Not Found'); // eslint-disable-line new-cap
case '426': return exceptions.UpgradeRequired('Upgrade Required'); // eslint-disable-line new-cap
case '429': return exceptions.TooManyRequestsError('Too Many Requests'); // eslint-disable-line new-cap
case '500': return exceptions.ServerError('Server Error'); // eslint-disable-line new-cap
case '503': return exceptions.DownForMaintenanceError('Down for Maintenance'); // eslint-disable-line new-cap
default: return exceptions.UnexpectedError(`Unexpected HTTP response: ${status}`); // eslint-disable-line new-cap
}
}
delete(url) {
return this.request('DELETE', url, null);
}
get(url) {
return this.request('GET', url, null);
}
post(url, body) {
return this.request('POST', url, body);
}
put(url, body) {
return this.request('PUT', url, body);
}
request(method, url, body) {
let requestBody, requestAborted;
let client = this.config.environment.ssl ? https : http;
let options = {
host: this.config.environment.server,
port: this.config.environment.port,
method,
path: url,
headers: this._headers()
};
if (body) {
requestBody = JSON.stringify(Util.convertObjectKeysToUnderscores(body));
options.headers['Content-Length'] = Buffer.byteLength(requestBody).toString();
}
return new Promise((resolve, reject) => {
let theRequest = client.request(options, (response) => {
let chunks = [];
response.on('data', (responseBody) => {
chunks.push(responseBody);
});
response.on('end', () => {
let buffer = Buffer.concat(chunks);
let error = this.checkHttpStatus(response.statusCode);
if (error) {
reject(error);
return;
}
if (buffer.length > 0) {
if (response.headers['content-encoding'] === 'gzip') {
zlib.gunzip(buffer, (gunzipError, result) => {
if (gunzipError) {
reject(gunzipError);
} else {
parseResponse(result.toString('utf8'));
}
});
} else {
parseResponse(buffer.toString('utf8'));
}
} else {
resolve();
}
});
response.on('error', function (err) {
let error = exceptions.UnexpectedError(`Unexpected response error: ${err}`); // eslint-disable-line new-cap
reject(error);
});
});
function parseResponse(responseBody) {
if (responseBody.match(/^\s+$/)) {
resolve();
} else {
new xml2js.Parser({
explicitRoot: true
}).parseString(responseBody, (err, result) => {
if (err) {
reject(err);
} else if (result) {
resolve(Util.convertNodeToObject(result));
}
});
}
}
function timeoutHandler() {
theRequest.abort();
requestAborted = true;
let error = exceptions.UnexpectedError('Request timed out'); // eslint-disable-line new-cap
reject(error);
}
theRequest.setTimeout(this.config.timeout, timeoutHandler);
let requestSocket = null;
theRequest.on('socket', (socket) => {
requestSocket = socket;
});
theRequest.on('error', err => {
if (requestAborted) { return; }
if (this.config.timeout > 0) {
requestSocket.removeListener('timeout', timeoutHandler);
}
let error = exceptions.UnexpectedError(`Unexpected request error: ${err}`); // eslint-disable-line new-cap
reject(error);
});
if (body) { theRequest.write(requestBody); }
theRequest.end();
});
}
_headers() {
return {
Authorization: this.authorizationHeader(),
'X-ApiVersion': this.config.apiVersion,
Accept: 'application/xml',
'Content-Type': 'application/json',
'User-Agent': `Braintree Node ${version}`,
'Accept-Encoding': 'gzip'
};
}
authorizationHeader() {
if (this.config.accessToken) {
return `Bearer ${this.config.accessToken}`;
} else if (this.config.clientId) {
return `Basic ${(new Buffer(this.config.clientId + ':' + this.config.clientSecret)).toString('base64')}`;
}
return `Basic ${(new Buffer(this.config.publicKey + ':' + this.config.privateKey)).toString('base64')}`;
}
}
module.exports = {Http: wrapPrototype(Http)};