Guest User

Untitled

a guest
Aug 20th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. /**
  2. * definition of core function
  3. *
  4. * @param {String} url URL to acess the API
  5. * @param {Object} initOptions Request body and options to be sent
  6. * @param {Object} Promise Promise of the fetch to be resolved or rejected
  7. * @return {Object} options extra options
  8. */
  9. core = (url, initOptions, promiseForFetch, options) => {
  10. fetch(url, initOptions).then((response) => {
  11. if (response.ok) {
  12. response.json().then((responseJSON) => {
  13. promiseForFetch.resolve(responseJSON);
  14. }).catch((parseError) => {
  15. // Parsing errors are caught and handled here
  16. if (options.parseErrorHandler) {
  17. options.parseErrorHandler(parseError);
  18. }else{
  19. this.dispatch(this.parseErrorHandler(parseError));
  20. }
  21. });
  22. } else {
  23. // Backend errors are caught and handled here
  24. if (options.backendErrorHandler) {
  25. options.backendErrorHandler(response);
  26. }else{
  27. this.dispatch(this.backendErrorHandler(response));
  28. }
  29. promiseForFetch.reject(response.text());
  30. }
  31. })
  32. .catch((networkError) => {
  33. // Network errors are caught and handled here
  34. if (options.networkErrorHandler) {
  35. options.networkErrorHandler(networkError);
  36. }else{
  37. this.dispatch(this.networkErrorHandler(networkError));
  38. }
  39.  
  40. // Re fetch the failed api once again in an exponential time frame
  41. const sleepTime = options.sleepTime || 1000;
  42. this.sleep(sleepTime).then(() => {
  43. const updatedOptions = { ...options, sleepTime: sleepTime * 2 };
  44. this.core(url, initOptions, promiseForFetch, updatedOptions);
  45. });
  46.  
  47. });
  48. }
Add Comment
Please, Sign In to add comment