summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pages/admin/application_settings/payload_downloader.js
blob: 8cecc1d3ef722cd7030486cdb7e8e08c73f360fb (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
import createFlash from '~/flash';
import axios from '~/lib/utils/axios_utils';
import { __ } from '~/locale';

export default class PayloadDownloader {
  constructor(trigger) {
    this.trigger = trigger;
  }

  init() {
    this.spinner = this.trigger.querySelector('.js-spinner');
    this.text = this.trigger.querySelector('.js-text');

    this.trigger.addEventListener('click', (event) => {
      event.preventDefault();

      return this.requestPayload();
    });
  }

  requestPayload() {
    this.spinner.classList.add('gl-display-inline');

    return axios
      .get(this.trigger.dataset.endpoint, {
        responseType: 'json',
      })
      .then(({ data }) => {
        PayloadDownloader.downloadFile(data);
      })
      .catch(() => {
        createFlash({
          message: __('Error fetching payload data.'),
        });
      })
      .finally(() => {
        this.spinner.classList.remove('gl-display-inline');
      });
  }

  static downloadFile(data) {
    const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });

    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = `${data.recorded_at.slice(0, 10)} payload.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(link.href);
  }
}