Welcome to mirror list, hosted at ThFree Co, Russian Federation.

actions.js « store « awards_app « emoji « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 427a504e038f5867ec5fca00967fbc65d2eede79 (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
import * as Sentry from '@sentry/browser';
import axios from '~/lib/utils/axios_utils';
import { normalizeHeaders } from '~/lib/utils/common_utils';
import { joinPaths } from '~/lib/utils/url_utility';
import { __ } from '~/locale';
import showToast from '~/vue_shared/plugins/global_toast';
import {
  SET_INITIAL_DATA,
  FETCH_AWARDS_SUCCESS,
  ADD_NEW_AWARD,
  REMOVE_AWARD,
} from './mutation_types';

export const setInitialData = ({ commit }, data) => commit(SET_INITIAL_DATA, data);

export const fetchAwards = async ({ commit, dispatch, state }, page = '1') => {
  try {
    const { data, headers } = await axios.get(joinPaths(gon.relative_url_root || '', state.path), {
      params: { per_page: 100, page },
    });
    const normalizedHeaders = normalizeHeaders(headers);
    const nextPage = normalizedHeaders['X-NEXT-PAGE'];

    commit(FETCH_AWARDS_SUCCESS, data);

    if (nextPage) {
      dispatch('fetchAwards', nextPage);
    }
  } catch (error) {
    Sentry.captureException(error);
  }
};

/**
 * Creates an intermediary award, used for display
 * until the real award is loaded from the backend.
 */
const newOptimisticAward = (name, state) => {
  const freeId = Math.min(...state.awards.map((a) => a.id), Number.MAX_SAFE_INTEGER) - 1;
  return {
    id: freeId,
    name,
    user: {
      id: window.gon.current_user_id,
      name: window.gon.current_user_fullname,
      username: window.gon.current_username,
    },
  };
};

export const toggleAward = async ({ commit, state }, name) => {
  const award = state.awards.find((a) => a.name === name && a.user.id === state.currentUserId);

  try {
    if (award) {
      commit(REMOVE_AWARD, award.id);

      await axios
        .delete(joinPaths(gon.relative_url_root || '', `${state.path}/${award.id}`))
        .catch((err) => {
          commit(ADD_NEW_AWARD, award);

          throw err;
        });

      showToast(__('Award removed'));
    } else {
      const optimisticAward = newOptimisticAward(name, state);

      commit(ADD_NEW_AWARD, optimisticAward);

      const { data } = await axios
        .post(joinPaths(gon.relative_url_root || '', state.path), {
          name,
        })
        .finally(() => {
          commit(REMOVE_AWARD, optimisticAward.id);
        });

      commit(ADD_NEW_AWARD, data);

      showToast(__('Award added'));
    }
  } catch (error) {
    Sentry.captureException(error);
  }
};