Skip to content

Instantly share code, notes, and snippets.

@rudyhuynh
Last active February 1, 2018 03:33
Show Gist options
  • Save rudyhuynh/9dbf09518b372dc7583e7eb36ee77a64 to your computer and use it in GitHub Desktop.
Save rudyhuynh/9dbf09518b372dc7583e7eb36ee77a64 to your computer and use it in GitHub Desktop.
A higher-order fetch that retry on error
import Rx from "rxjs";
const MAX_RETRY = 3
const RETRY_DELAY = 500
export const onErrorRetryHOF = fetch => (input, init) => {
let count = 0;
return Rx.Observable.defer(() =>
Rx.Observable.fromPromise(
fetch(input, init).then(resp => {
if ((resp.status + "").startsWith("5")) throw resp;
return resp;
})
)
)
.retryWhen(errors => {
return errors.mergeMap(error => {
if (++count >= MAX_RETRY) {
return Rx.Observable.throw(error);
} else {
return Rx.Observable.of(error).delay(RETRY_DELAY);
}
});
})
.toPromise()
.then(
resp => resp,
resp => {
if (resp.status === 500) return resp;
throw resp;
}
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment