summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/projects/gke_cluster_dropdowns/store/actions.js
blob: 73f1e17f3798917871f9e9948f07382946d5d258 (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
89
90
91
92
93
94
95
96
/* global gapi */
import createFlash, { hideFlash } from '~/flash';
import { s__, sprintf } from '~/locale';

import * as types from './mutation_types';

export const setProject = ({ commit }, selectedProject) => {
  commit(types.SET_PROJECT, selectedProject);
};

export const setZone = ({ commit }, selectedZone) => {
  commit(types.SET_ZONE, selectedZone);
};

export const setMachineType = ({ commit }, selectedMachineType) => {
  commit(types.SET_MACHINE_TYPE, selectedMachineType);
};

const displayError = (resp, errorMessage) => {
  if (resp.result && resp.result.error) {
    createFlash(sprintf(errorMessage, { error: resp.result.error.message }));
  }
};

const hideError = () => {
  const flashEl = document.querySelector('.flash-alert');

  if (flashEl) {
    hideFlash(flashEl);
  }
};

const gapiRequest = ({ service, params, commit, mutation, payloadKey, errorMessage }) =>
  new Promise((resolve, reject) => {
    const request = service.list(params);

    return request.then(
      resp => {
        const { result } = resp;

        hideError();
        commit(mutation, result[payloadKey]);

        resolve();
      },
      resp => {
        displayError(resp, errorMessage);

        reject();
      },
    );
  });

export const getProjects = ({ commit }) =>
  gapiRequest({
    service: gapi.client.cloudresourcemanager.projects,
    params: {},
    commit,
    mutation: types.SET_PROJECTS,
    payloadKey: 'projects',
    errorMessage: s__(
      'ClusterIntegration|An error occured while trying to fetch your projects: %{error}',
    ),
  });

export const getZones = ({ commit, state }) =>
  gapiRequest({
    service: gapi.client.compute.zones,
    params: {
      project: state.selectedProject.projectId,
    },
    commit,
    mutation: types.SET_ZONES,
    payloadKey: 'items',
    errorMessage: s__(
      'ClusterIntegration|An error occured while trying to fetch project zones: %{error}',
    ),
  });

export const getMachineTypes = ({ commit, state }) =>
  gapiRequest({
    service: gapi.client.compute.machineTypes,
    params: {
      project: state.selectedProject.projectId,
      zone: state.selectedZone,
    },
    commit,
    mutation: types.SET_MACHINE_TYPES,
    payloadKey: 'items',
    errorMessage: s__(
      'ClusterIntegration|An error occured while trying to fetch zone machine types: %{error}',
    ),
  });

// prevent babel-plugin-rewire from generating an invalid default during karma tests
export default () => {};