aboutsummaryrefslogtreecommitdiff
path: root/webAO/services/request.js
blob: 0d706d41d0b0fb1193ac753b75d1060047cfafeb (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
 * Make a GET request for a specific URI.
 * @param {string} url the URI to be requested
 * @returns response data
 * @throws {Error} if status code is not 2xx, or a network error occurs
 */
export async function requestBuffer(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.responseType = "arraybuffer";
    xhr.addEventListener("error", () => {
      const err = new Error(`Request for ${url} failed: ${xhr.statusText}`);
      err.code = xhr.status;
      reject(err);
    });
    xhr.addEventListener("abort", () => {
      const err = new Error(`Request for ${url} was aborted!`);
      err.code = xhr.status;
      reject(err);
    });
    xhr.addEventListener("load", () => {
      if (xhr.status < 200 || xhr.status >= 300) {
        const err = new Error(
          `Request for ${url} failed with status code ${xhr.status}`,
        );
        err.code = xhr.status;
        reject(err);
      } else {
        resolve(xhr.response);
      }
    });
    xhr.open("GET", url, true);
    xhr.send();
  });
}

/**
 * Make a GET request for a specific URI.
 * @param {string} url the URI to be requested
 * @returns response data
 * @throws {Error} if status code is not 2xx, or a network error occurs
 */
export const request = async (url) =>
  new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.responseType = "text";
    xhr.addEventListener("error", () => {
      const err = new Error(`Request for ${url} failed: ${xhr.statusText}`);
      err.code = xhr.status;
      reject(err);
    });
    xhr.addEventListener("abort", () => {
      const err = new Error(`Request for ${url} was aborted!`);
      err.code = xhr.status;
      reject(err);
    });
    xhr.addEventListener("load", () => {
      if (xhr.status < 200 || xhr.status >= 300) {
        const err = new Error(
          `Request for ${url} failed with status code ${xhr.status}`,
        );
        err.code = xhr.status;
        reject(err);
      } else {
        resolve(xhr.response);
      }
    });
    xhr.open("GET", url, true);
    xhr.send();
  });
export default request;