-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrequest.js
More file actions
51 lines (44 loc) · 1.43 KB
/
request.js
File metadata and controls
51 lines (44 loc) · 1.43 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
const _request = require('request');
const { ProtocolError } = require('./errors');
/**
* Light wrapper around request.js. Returns a Promise and handles a couple
* Google-specific protocol interpretations.
*
* @param {Object} options Forwarded to request.js
* @return {Promise} resolves with the request.js response
*/
const request = async (options) =>
new Promise((resolve, reject) => {
_request(options, (err, res) => {
if (err) {
reject(err);
return;
}
const contentType = res.headers['content-type'];
// If options.json=true, then request.js will automatically parse response
// bodies as JSON. Some calls may not be able to pass options.json=true
// (for example, if the request body is not JSON), but may still receive
// a JSON response. Accordingly, this condition attempts to parse a JSON
// response, but only if it wasn't already parsed by request.js.
if (
contentType &&
contentType.startsWith('application/json') &&
!options.json
) {
try {
res.body = JSON.parse(res.body);
} catch (e) {
reject(new ProtocolError(e.message, res));
return;
}
}
if (res.body && res.body.error) {
reject(
new ProtocolError(res.body.error.message || 'API response error', res)
);
return;
}
resolve(res);
});
});
module.exports = request;