This repository was archived by the owner on Sep 2, 2025. It is now read-only.
forked from locize/locize-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.js
More file actions
53 lines (50 loc) · 2.22 KB
/
request.js
File metadata and controls
53 lines (50 loc) · 2.22 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
const package = require('./package.json');
const fetch = require('node-fetch');
const HttpsProxyAgent = require('https-proxy-agent');
const https = require('https');
const CacheableLookup = require('cacheable-lookup');
const cacheable = new CacheableLookup();
cacheable.install(https.globalAgent);
const httpProxy = process.env.http_proxy || process.env.HTTP_PROXY || process.env.https_proxy || process.env.HTTPS_PROXY;
module.exports = (url, options, callback) => {
if (httpProxy) {
const httpsProxyAgent = new HttpsProxyAgent(httpProxy);
cacheable.install(httpsProxyAgent);
options.agent = httpsProxyAgent;
}
options.headers = options.headers || {};
options.headers['User-Agent'] = `${package.name}/v${package.version} (node/${process.version}; ${process.platform} ${process.arch})`;
options.headers['X-User-Agent'] = options.headers['User-Agent'];
if (options.body || options.method !== 'get') options.headers['Content-Type'] = 'application/json';
if (options.body) {
if (typeof options.body !== 'string') {
options.body = JSON.stringify(options.body);
}
}
if (options.headers['Authorization'] === undefined) delete options.headers['Authorization'];
fetch(url, options).then((res) => {
if (res.headers.get('content-type') && res.headers.get('content-type').indexOf('json') > 0) {
return new Promise((resolve, reject) => res.json().then((obj) => resolve({ res, obj })).catch(reject));
} else {
return { res };
}
}).then((ret) => callback(null, ret.res, ret.obj)).catch((err) => {
if (err && err.message && (
err.message.indexOf('ENOTFOUND') > -1 ||
err.message.indexOf('ENODATA') > -1 ||
err.message.indexOf('ENOENT') > -1 // Windows: name exists, but not this record type
)) {
setTimeout(() => {
fetch(url, options).then((res) => {
if (res.headers.get('content-type') && res.headers.get('content-type').indexOf('json') > 0) {
return new Promise((resolve, reject) => res.json().then((obj) => resolve({ res, obj })).catch(reject));
} else {
return { res };
}
}).then((ret) => callback(null, ret.res, ret.obj)).catch(callback);
}, 5000);
return;
}
callback(err);
});
};