-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
70 lines (56 loc) · 2.11 KB
/
index.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
const _ = require('lodash');
const request = require('request-promise');
const Promise = require('bluebird');
const cache = require('./src/cache');
const passedInAuth = require('./src/passedInAuth');
const re = require('./src/requestEmitter');
// TODO: get from options? Or setup config
let logger = console.log;
const requestBuilder = (passedInOptions) => {
// TODO: can set other defaults here that can be overriden by assign!
const defaultOptions = {
method: 'GET',
};
const options = _.assign(defaultOptions, passedInOptions);
cache.setKeyGenFunc(options);
options.uri = options.url || options.uri;
const delay = ms => new Promise((resolve) => {
setTimeout(resolve, ms);
});
// pull out after requestBuilder
const retryLoop = (error) => {
if (options.timesToRetry === undefined
|| options.timesToRetry === null
|| options.timesToRetry > 0) {
if (options.timesToRetry) {
options.timesToRetry -= 1;
}
// Look for a retryAttempts property in options
options.retryAttempts = (options.retryAttempts || 0) + 1;
logger('Retrying in %sms', 200 << options.retryAttempts); // eslint-disable-line no-bitwise
return delay(200 << options.retryAttempts) // eslint-disable-line no-bitwise
.then(() => requestBuilder(options));
}
logger(`No response from url ${options.uri} during any calls or re-tries`);
return Promise.reject(error);
};
// Try pre-set auth token first
return passedInAuth(options, retryLoop);
};
/**
* Return a request.js instance that wraps a custom request builder responsible for authenticating
* all calls with an OAuth Bearer token from Auth0, whether retrieved via a client credentials grant
* flow (preferred) or via delegation.
*/
module.exports = request.defaults(requestBuilder);
module.exports.credentialCache = cache.cache;
module.exports.defaultCache = cache.defaultCache;
module.exports.setCredentialCache = (altCache) => {
cache.setCache(altCache);
};
module.exports.setLogger = (l) => {
logger = l;
cache.setLogger(logger);
passedInAuth.setLogger(logger);
};
module.exports.requestEmitter = re;