You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

httpUtils.js 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { timeoutPromise } from './timeoutPromise';
  2. /**
  3. * The number of milliseconds before deciding that we need retry a fetch request.
  4. *
  5. * @type {number}
  6. */
  7. const RETRY_TIMEOUT = 3000;
  8. /**
  9. * Wrapper around fetch GET requests to handle json-ifying the response
  10. * and logging errors.
  11. *
  12. * @param {string} url - The URL to perform a GET against.
  13. * @param {?boolean} retry - Whether the request will be retried after short timeout.
  14. * @returns {Promise<Object>} The response body, in JSON format, will be
  15. * through the Promise.
  16. */
  17. export function doGetJSON(url, retry) {
  18. const fetchPromise = fetch(url)
  19. .then(response => {
  20. const jsonify = response.json();
  21. if (response.ok) {
  22. return jsonify;
  23. }
  24. return jsonify
  25. .then(result => Promise.reject(result));
  26. });
  27. if (retry) {
  28. return timeoutPromise(fetchPromise, RETRY_TIMEOUT)
  29. .catch(response => {
  30. if (response.status >= 400 && response.status < 500) {
  31. return Promise.reject(response);
  32. }
  33. return timeoutPromise(fetchPromise, RETRY_TIMEOUT);
  34. });
  35. }
  36. return fetchPromise;
  37. }