summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/jira_connect/subscriptions/store/actions.js
blob: 4a83ee8671d6b2ed8ecec06bfa58e120736cc003 (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
import { fetchSubscriptions as fetchSubscriptionsREST } from '~/jira_connect/subscriptions/api';
import { getCurrentUser } from '~/rest_api';
import { addJiraConnectSubscription } from '~/api/integrations_api';
import {
  I18N_ADD_SUBSCRIPTION_SUCCESS_ALERT_TITLE,
  I18N_ADD_SUBSCRIPTION_SUCCESS_ALERT_MESSAGE,
  INTEGRATIONS_DOC_LINK,
  I18N_DEFAULT_SUBSCRIPTIONS_ERROR_MESSAGE,
} from '../constants';
import { getJwt } from '../utils';
import {
  SET_SUBSCRIPTIONS,
  SET_SUBSCRIPTIONS_LOADING,
  SET_SUBSCRIPTIONS_ERROR,
  ADD_SUBSCRIPTION_LOADING,
  ADD_SUBSCRIPTION_ERROR,
  SET_ALERT,
  SET_CURRENT_USER,
  SET_CURRENT_USER_ERROR,
} from './mutation_types';

export const fetchSubscriptions = async ({ commit }, subscriptionsPath) => {
  commit(SET_SUBSCRIPTIONS_LOADING, true);

  try {
    const data = await fetchSubscriptionsREST(subscriptionsPath);
    commit(SET_SUBSCRIPTIONS, data.data.subscriptions);
  } catch {
    commit(SET_SUBSCRIPTIONS_ERROR, true);
    commit(SET_ALERT, { message: I18N_DEFAULT_SUBSCRIPTIONS_ERROR_MESSAGE, variant: 'danger' });
  } finally {
    commit(SET_SUBSCRIPTIONS_LOADING, false);
  }
};

export const loadCurrentUser = async ({ commit }, accessToken) => {
  try {
    const { data: user } = await getCurrentUser({
      headers: { Authorization: `Bearer ${accessToken}` },
    });

    commit(SET_CURRENT_USER, user);
  } catch (e) {
    commit(SET_CURRENT_USER_ERROR, e);
  }
};

export const addSubscription = async (
  { commit, state, dispatch },
  { namespacePath, subscriptionsPath },
) => {
  try {
    commit(ADD_SUBSCRIPTION_LOADING, true);

    await addJiraConnectSubscription(namespacePath, {
      jwt: await getJwt(),
      accessToken: state.accessToken,
    });

    commit(SET_ALERT, {
      title: I18N_ADD_SUBSCRIPTION_SUCCESS_ALERT_TITLE,
      message: I18N_ADD_SUBSCRIPTION_SUCCESS_ALERT_MESSAGE,
      linkUrl: INTEGRATIONS_DOC_LINK,
      variant: 'success',
    });

    dispatch('fetchSubscriptions', subscriptionsPath);
  } catch (e) {
    commit(ADD_SUBSCRIPTION_ERROR, e);
  } finally {
    commit(ADD_SUBSCRIPTION_LOADING, false);
  }
};