UNPKG

rxjs-retry-delay

Version:

RxJS retry pipeable operator with delay and max attempts strategy for RxJS >= 6

23 lines 1.19 kB
import { throwError, timer } from 'rxjs'; import { finalize, mergeMap as switchMap, retryWhen, tap } from 'rxjs/operators'; export const retryWithDelay = ({ delay = 1000, maxRetryAttempts = 3, scalingFactor = 1, excludedStatusCodes = [], resetRetryCountOnEmission = false }) => (source) => { let retryAttempts = 0; return source.pipe(retryWhen((attempts) => { return attempts.pipe(switchMap((error) => { // if maximum number of retries have been met // or response is a status code we don't wish to retry, throw error if (++retryAttempts > maxRetryAttempts || excludedStatusCodes.find((e) => e === error.status)) { return throwError(error); } const tryAfter = delay * Math.pow(scalingFactor, (retryAttempts - 1)); console.log(`Attempt ${retryAttempts}: retrying in ${tryAfter}ms`); // retry after 1s, 2s, etc... return timer(tryAfter); }), finalize(() => console.log('Done with retrying.'))); }), tap(() => { if (resetRetryCountOnEmission) { retryAttempts = 0; } })); }; //# sourceMappingURL=retry-delay.operator.js.map