Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

httpUtils.js 1.4KB

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