summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/utils/poll_until_complete.js
blob: 3545db3a2278950aa7e5830d908ae158b7caeffb (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
import axios from '~/lib/utils/axios_utils';
import httpStatusCodes from './http_status';
import Poll from './poll';

/**
 * Polls an endpoint until it returns either a 200 OK or a error status.
 * The Poll-Interval header in the responses are used to determine how
 * frequently to poll.
 *
 * Once a 200 OK is received, the promise resolves with that response. If an
 * error status is received, the promise rejects with the error.
 *
 * @param {string} url - The URL to poll.
 * @param {Object} [config] - The config to provide to axios.get().
 * @returns {Promise}
 */
export default (url, config = {}) =>
  new Promise((resolve, reject) => {
    const eTagPoll = new Poll({
      resource: {
        axiosGet(data) {
          return axios.get(data.url, {
            headers: {
              'Content-Type': 'application/json',
            },
            ...data.config,
          });
        },
      },
      data: { url, config },
      method: 'axiosGet',
      successCallback: (response) => {
        if (response.status === httpStatusCodes.OK) {
          resolve(response);
          eTagPoll.stop();
        }
      },
      errorCallback: reject,
    });

    eTagPoll.makeRequest();
  });