Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * definition of core function
- *
- * @param {String} url URL to acess the API
- * @param {Object} initOptions Request body and options to be sent
- * @param {Object} Promise Promise of the fetch to be resolved or rejected
- * @return {Object} options extra options
- */
- core = (url, initOptions, promiseForFetch, options) => {
- fetch(url, initOptions).then((response) => {
- if (response.ok) {
- response.json().then((responseJSON) => {
- promiseForFetch.resolve(responseJSON);
- }).catch((parseError) => {
- // Parsing errors are caught and handled here
- if (options.parseErrorHandler) {
- options.parseErrorHandler(parseError);
- }else{
- this.dispatch(this.parseErrorHandler(parseError));
- }
- });
- } else {
- // Backend errors are caught and handled here
- if (options.backendErrorHandler) {
- options.backendErrorHandler(response);
- }else{
- this.dispatch(this.backendErrorHandler(response));
- }
- promiseForFetch.reject(response.text());
- }
- })
- .catch((networkError) => {
- // Network errors are caught and handled here
- if (options.networkErrorHandler) {
- options.networkErrorHandler(networkError);
- }else{
- this.dispatch(this.networkErrorHandler(networkError));
- }
- // Re fetch the failed api once again in an exponential time frame
- const sleepTime = options.sleepTime || 1000;
- this.sleep(sleepTime).then(() => {
- const updatedOptions = { ...options, sleepTime: sleepTime * 2 };
- this.core(url, initOptions, promiseForFetch, updatedOptions);
- });
- });
- }
Add Comment
Please, Sign In to add comment