aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/utils/fetch.js
blob: ef695193a9ecc71012b56100def573c92f21c96b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// ==========================================================================
// Fetch wrapper
// Using XHR to avoid issues with older browsers
// ==========================================================================

export default function fetch(url, responseType = 'text') {
  return new Promise((resolve, reject) => {
    try {
      const request = new XMLHttpRequest();

      // Check for CORS support
      if (!('withCredentials' in request)) {
        return;
      }

      request.addEventListener('load', () => {
        if (responseType === 'text') {
          try {
            resolve(JSON.parse(request.responseText));
          } catch (e) {
            resolve(request.responseText);
          }
        } else {
          resolve(request.response);
        }
      });

      request.addEventListener('error', () => {
        throw new Error(request.status);
      });

      request.open('GET', url, true);

      // Set the required response type
      request.responseType = responseType;

      request.send();
    } catch (e) {
      reject(e);
    }
  });
}