summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pipelines/pipeline_details_mediator.js
blob: 74c5fc45644c6383788e04a4e8a72efc8aee96a8 (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
72
73
74
75
76
77
78
79
import Visibility from 'visibilityjs';
import PipelineStore from './stores/pipeline_store';
import { deprecatedCreateFlash as Flash } from '../flash';
import Poll from '../lib/utils/poll';
import { __ } from '../locale';
import PipelineService from './services/pipeline_service';

export default class pipelinesMediator {
  constructor(options = {}) {
    this.options = options;
    this.store = new PipelineStore();
    this.service = new PipelineService(options.endpoint);

    this.state = {};
    this.state.isLoading = false;
  }

  fetchPipeline() {
    this.poll = new Poll({
      resource: this.service,
      method: 'getPipeline',
      data: this.store.state.expandedPipelines ? this.getExpandedParameters() : undefined,
      successCallback: this.successCallback.bind(this),
      errorCallback: this.errorCallback.bind(this),
    });

    if (!Visibility.hidden()) {
      this.state.isLoading = true;
      this.poll.makeRequest();
    } else {
      this.refreshPipeline();
    }

    Visibility.change(() => {
      if (!Visibility.hidden()) {
        this.poll.restart();
      } else {
        this.stopPipelinePoll();
      }
    });
  }

  successCallback(response) {
    this.state.isLoading = false;
    this.store.storePipeline(response.data);
  }

  errorCallback() {
    this.state.isLoading = false;
    Flash(__('An error occurred while fetching the pipeline.'));
  }

  refreshPipeline() {
    this.stopPipelinePoll();

    return this.service
      .getPipeline()
      .then((response) => this.successCallback(response))
      .catch(() => this.errorCallback())
      .finally(() =>
        this.poll.restart(
          this.store.state.expandedPipelines ? this.getExpandedParameters() : undefined,
        ),
      );
  }

  stopPipelinePoll() {
    this.poll.stop();
  }

  /**
   * Backend expects paramets in the following format: `expanded[]=id&expanded[]=id`
   */
  getExpandedParameters() {
    return {
      expanded: this.store.state.expandedPipelines,
    };
  }
}