-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticatedCall.js
49 lines (47 loc) · 1.41 KB
/
authenticatedCall.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
const querystring = require('querystring');
const https = require('https');
const authenticatedCall = (url, options) =>
new Promise((resolve, reject) => {
const body = options.body && querystring.stringify(options.body);
const json = options.json && JSON.stringify(options.json);
const query = options.query
? `?${querystring.stringify(options.query)}`
: '';
if (body) {
options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
options.headers['Content-Length'] = body.length;
}
if (json) {
options.headers['Content-Type'] = 'application/json';
options.headers['Content-Length'] = json.length;
}
const req = https.request(url + query, options, res => {
if (res.statusCode === 200 || res.statusCode === 201) {
res.data = '';
res.on('data', d => {
res.data += d;
});
res.on('end', () => {
const parsedResponse = JSON.parse(res.data);
if (parsedResponse.error) {
reject(parsedResponse);
}
resolve(parsedResponse);
});
} else {
const { statusCode, statusMessage } = res;
reject({ statusCode, statusMessage });
}
});
req.on('error', error => {
reject(error);
});
if (body) {
req.write(body);
}
if (json) {
req.write(json);
}
req.end();
});
module.exports = authenticatedCall;