Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Improved Retry Failed Request
  • Loading branch information
Jacob Goh committed Nov 10, 2018
1 parent 3098b48 commit e194f4f
Showing 1 changed file with 38 additions and 3 deletions.
41 changes: 38 additions & 3 deletions index.js
@@ -1,12 +1,14 @@
const { BehaviorSubject, from, of } = require('rxjs');
const { BehaviorSubject, from, of, timer } = require('rxjs');
const {
map,
distinct,
filter,
mergeMap,
retry,
catchError,
share
share,
retryWhen,
finalize
} = require('rxjs/operators');
const rp = require('request-promise-native');
const normalizeUrl = require('normalize-url');
Expand All @@ -18,6 +20,33 @@ const baseUrl = `https://imdb.com`;
const maxConcurrentReq = 10;
const maxRetries = 5;

const genericRetryStrategy = ({
maxRetryAttempts,
scalingDuration,
excludedStatusCodes
}) => attempts => {
return attempts.pipe(
mergeMap((error, i) => {
const retryAttempt = i + 1;
// if maximum number of retries have been met
// or response is a status code we don't wish to retry, throw error
if (
retryAttempt > maxRetryAttempts ||
excludedStatusCodes.find(e => e === error.status)
) {
return throwError(error);
}
console.log(
`Attempt ${retryAttempt}: retrying in ${retryAttempt *
scalingDuration}ms`
);
// retry after 1s, 2s, etc...
return timer(retryAttempt * scalingDuration);
}),
finalize(() => console.log('We are done!'))
);
};

const allUrl$ = new BehaviorSubject(baseUrl);

const uniqueUrl$ = allUrl$.pipe(
Expand All @@ -33,7 +62,13 @@ const urlAndDOM$ = uniqueUrl$.pipe(
mergeMap(
url => {
return from(rp(url)).pipe(
retry(maxRetries),
retryWhen(
genericRetryStrategy({
maxRetryAttempts: maxRetries,
scalingDuration: 3000,
excludedStatusCodes: []
})
),
catchError(error => {
const { uri } = error.options;
console.log(`Error requesting ${uri} after ${maxRetries} retries.`);
Expand Down

0 comments on commit e194f4f

Please sign in to comment.