rx-retry
Version:
Package for retries in RxJS, Promises and NestJS
42 lines (41 loc) • 2.05 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveWithRetry = void 0;
const rxjs_1 = require("rxjs");
const retry_backoff_1 = require("../operators/retry-backoff");
const resolve_retry_config_1 = require("./resolve-retry-config");
/**
* Retry a promise with exponential backoff.
* ```ts
const prm = new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Promise error'));
}, 1000);
});
const configuration: ResolveRetryConfig = {
timeoutTime: 5000, // set timeout to fail the promise and retry, default is 0
useJitter: true, // backoff strategy with random + exponantial delay, default is true
retryStrategy: {
initialInterval: 1000, // ms
maxRetries: 3,
maxInterval: 10000, // ms
shouldRetry: (error) => true, // check if retry needed, default is always true
}
}
const res = await resolveWithRetry(prm, configuration);
* ```
* @param promise - Promise to resolve
* @param config - Configuration for retry, can be number as the initial interval, OR ResolveRetryConfig
* @returns Resolved value of the promise with type T (Generic)
*/
function resolveWithRetry(promise, config) {
const selectedConfig = typeof config === 'number'
? { ...resolve_retry_config_1.DEFAULT_RESOLVE_RETRY_CONFIG, retryStrategy: { initialInterval: config } }
: config;
const { retryStrategy, useJitter = resolve_retry_config_1.DEFAULT_RESOLVE_RETRY_CONFIG.useJitter, timeoutTime = resolve_retry_config_1.DEFAULT_RESOLVE_RETRY_CONFIG.timeoutTime, } = selectedConfig;
retryStrategy.backoffDelay ??= useJitter ? retry_backoff_1.backoffDelayWithRandom : retry_backoff_1.exponentialBackoffDelay;
const obs = (0, rxjs_1.from)(promise).pipe((0, rxjs_1.timeout)(timeoutTime), (0, retry_backoff_1.retryBackoff)(retryStrategy));
return (0, rxjs_1.lastValueFrom)(obs);
}
exports.resolveWithRetry = resolveWithRetry;
//# sourceMappingURL=resolve-retry.js.map