2019-08-13 13:34:44 +00:00
|
|
|
import { timeoutPromise } from './timeoutPromise';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The number of milliseconds before deciding that we need retry a fetch request.
|
|
|
|
*
|
|
|
|
* @type {number}
|
|
|
|
*/
|
|
|
|
const RETRY_TIMEOUT = 3000;
|
|
|
|
|
2018-03-23 16:37:04 +00:00
|
|
|
/**
|
|
|
|
* Wrapper around fetch GET requests to handle json-ifying the response
|
|
|
|
* and logging errors.
|
|
|
|
*
|
|
|
|
* @param {string} url - The URL to perform a GET against.
|
2019-08-13 13:34:44 +00:00
|
|
|
* @param {?boolean} retry - Whether the request will be retried after short timeout.
|
2022-03-08 09:10:30 +00:00
|
|
|
* @param {?Object} options - The request options.
|
2018-03-23 16:37:04 +00:00
|
|
|
* @returns {Promise<Object>} The response body, in JSON format, will be
|
|
|
|
* through the Promise.
|
|
|
|
*/
|
2022-07-29 13:18:14 +00:00
|
|
|
export function doGetJSON(url: string, retry?: boolean, options?: Object) {
|
2022-03-08 09:10:30 +00:00
|
|
|
const fetchPromise = fetch(url, options)
|
2018-03-23 16:37:04 +00:00
|
|
|
.then(response => {
|
|
|
|
const jsonify = response.json();
|
|
|
|
|
|
|
|
if (response.ok) {
|
|
|
|
return jsonify;
|
|
|
|
}
|
|
|
|
|
|
|
|
return jsonify
|
|
|
|
.then(result => Promise.reject(result));
|
|
|
|
});
|
2019-08-13 13:34:44 +00:00
|
|
|
|
|
|
|
if (retry) {
|
|
|
|
return timeoutPromise(fetchPromise, RETRY_TIMEOUT)
|
|
|
|
.catch(response => {
|
|
|
|
if (response.status >= 400 && response.status < 500) {
|
|
|
|
return Promise.reject(response);
|
|
|
|
}
|
|
|
|
|
|
|
|
return timeoutPromise(fetchPromise, RETRY_TIMEOUT);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return fetchPromise;
|
2018-03-23 16:37:04 +00:00
|
|
|
}
|