summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/projects/gke_cluster_dropdowns/index.js
blob: 729b9404b641701afa86724c7bffb8ec79c34d49 (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
80
81
82
83
84
85
86
87
88
/* global gapi */
import Vue from 'vue';
import Flash from '~/flash';
import GkeProjectIdDropdown from './components/gke_project_id_dropdown.vue';
import GkeZoneDropdown from './components/gke_zone_dropdown.vue';
import GkeMachineTypeDropdown from './components/gke_machine_type_dropdown.vue';
import * as CONSTANTS from './constants';

const mountComponent = (entryPoint, component, componentName, extraProps = {}) => {
  const el = document.querySelector(entryPoint);
  if (!el) return false;

  const hiddenInput = el.querySelector('input');

  return new Vue({
    el,
    components: {
      [componentName]: component,
    },
    render: createElement =>
      createElement(componentName, {
        props: {
          fieldName: hiddenInput.getAttribute('name'),
          fieldId: hiddenInput.getAttribute('id'),
          defaultValue: hiddenInput.value,
          ...extraProps,
        },
      }),
  });
};

const mountGkeProjectIdDropdown = () => {
  const entryPoint = '.js-gcp-project-id-dropdown-entry-point';
  const el = document.querySelector(entryPoint);

  mountComponent(entryPoint, GkeProjectIdDropdown, 'gke-project-id-dropdown', {
    docsUrl: el.dataset.docsurl,
  });
};

const mountGkeZoneDropdown = () => {
  mountComponent('.js-gcp-zone-dropdown-entry-point', GkeZoneDropdown, 'gke-zone-dropdown');
};

const mountGkeMachineTypeDropdown = () => {
  mountComponent(
    '.js-gcp-machine-type-dropdown-entry-point',
    GkeMachineTypeDropdown,
    'gke-machine-type-dropdown',
  );
};

const gkeDropdownErrorHandler = () => {
  Flash(CONSTANTS.GCP_API_ERROR);
};

const initializeGapiClient = () => {
  const el = document.querySelector('.js-gke-cluster-creation');
  if (!el) return false;

  return gapi.client
    .init({
      discoveryDocs: [
        CONSTANTS.GCP_API_CLOUD_BILLING_ENDPOINT,
        CONSTANTS.GCP_API_CLOUD_RESOURCE_MANAGER_ENDPOINT,
        CONSTANTS.GCP_API_COMPUTE_ENDPOINT,
      ],
    })
    .then(() => {
      gapi.client.setToken({ access_token: el.dataset.token });

      mountGkeProjectIdDropdown();
      mountGkeZoneDropdown();
      mountGkeMachineTypeDropdown();
    })
    .catch(gkeDropdownErrorHandler);
};

const initGkeDropdowns = () => {
  if (!gapi) {
    gkeDropdownErrorHandler();
    return false;
  }

  return gapi.load('client', initializeGapiClient);
};

export default initGkeDropdowns;