auth0
Version:
Auth0 Node.js SDK for the Management API v2.
60 lines (59 loc) • 2.56 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
const MAX_REQUEST_RETRY_JITTER = 250;
const MAX_REQUEST_RETRY_DELAY = 10000;
const DEFAULT_NUMBER_RETRIES = 3;
const MAX_NUMBER_RETRIES = 10;
const BASE_DELAY = 500;
/**
* @private
* Function that returns a random int between a configurable min and max.
* @param min The min value
* @param max The max value
* @returns {number} The random generated value
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
}
/**
* @private
* Function that returns a promise which resolves after a configurable amount of milliseconds
* @param delay value to be used for the delay
* @returns {Promise} A delayed promise
*/
function pause(delay) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve) => setTimeout(resolve, delay));
});
}
/**
* @private
* Function that retries the provided action callback for a configurable amount of time, defaults to 3.
*/
export function retry(action, { maxRetries, retryWhen }) {
const nrOfTriesToAttempt = Math.min(MAX_NUMBER_RETRIES, maxRetries !== null && maxRetries !== void 0 ? maxRetries : DEFAULT_NUMBER_RETRIES);
let nrOfTries = 0;
const retryAndWait = () => __awaiter(this, void 0, void 0, function* () {
let result;
result = yield action();
if ((retryWhen || [429]).includes(result.status) && nrOfTries < nrOfTriesToAttempt) {
nrOfTries++;
let wait = BASE_DELAY * Math.pow(2, nrOfTries - 1);
wait = getRandomInt(wait + 1, wait + MAX_REQUEST_RETRY_JITTER);
wait = Math.min(wait, MAX_REQUEST_RETRY_DELAY);
yield pause(wait);
result = yield retryAndWait();
}
return result;
});
return retryAndWait();
}