Last active
February 1, 2018 03:33
-
-
Save rudyhuynh/9dbf09518b372dc7583e7eb36ee77a64 to your computer and use it in GitHub Desktop.
A higher-order fetch that retry on error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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