All files / app/assets/javascripts/import_entities/import_projects/store actions.js

82.72% Statements 67/81
44.83% Branches 13/29
81.25% Functions 26/32
83.33% Lines 60/72

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206                            3x 1x 3x 1x 8x 14x   8x 8x     1x         1x 2x     1x 2x     1x       1x     1x 1x     2x       1x 6x 6x   6x   6x                 3x 3x     3x   3x 1x           1x   2x           2x         1x 3x 3x   3x   3x 3x               1x           2x 2x                   2x       2x       1x 2x         2x   2x       2x                       2x 2x     2x                 1x 2x 2x     1x     1x       1x       1x 1x   1x     1x                        
import Visibility from 'visibilityjs';
import createFlash from '~/flash';
import axios from '~/lib/utils/axios_utils';
import { convertObjectPropsToCamelCase } from '~/lib/utils/common_utils';
import httpStatusCodes from '~/lib/utils/http_status';
import Poll from '~/lib/utils/poll';
import { capitalizeFirstCharacter } from '~/lib/utils/text_utility';
import { visitUrl, objectToQuery } from '~/lib/utils/url_utility';
import { s__, sprintf } from '~/locale';
import { isProjectImportable } from '../utils';
import * as types from './mutation_types';
 
let eTagPoll;
 
const hasRedirectInError = (e) => e?.response?.data?.error?.redirect;
const redirectToUrlInError = (e) => visitUrl(e.response.data.error.redirect);
const tooManyRequests = (e) => e.response.status === httpStatusCodes.TOO_MANY_REQUESTS;
const pathWithParams = ({ path, ...params }) => {
  const filteredParams = Object.fromEntries(
    Object.entries(params).filter(([, value]) => value !== ''),
  );
  const queryString = objectToQuery(filteredParams);
  return queryString ? `${path}?${queryString}` : path;
};
 
const isRequired = () => {
  // eslint-disable-next-line @gitlab/require-i18n-strings
  throw new Error('param is required');
};
 
const clearJobsEtagPoll = () => {
  eTagPoll = null;
};
 
const stopJobsPolling = () => {
  Eif (eTagPoll) eTagPoll.stop();
};
 
const restartJobsPolling = () => {
  if (eTagPoll) eTagPoll.restart();
};
 
const setImportTarget = ({ commit }, { repoId, importTarget }) =>
  commit(types.SET_IMPORT_TARGET, { repoId, importTarget });
 
const importAll = ({ state, dispatch }) => {
  return Promise.all(
    state.repositories
      .filter(isProjectImportable)
      .map((r) => dispatch('fetchImport', r.importSource.id)),
  );
};
 
const fetchReposFactory = ({ reposPath = isRequired() }) => ({ state, commit }) => {
  const nextPage = state.pageInfo.page + 1;
  commit(types.REQUEST_REPOS);
 
  const { provider, filter } = state;
 
  return axios
    .get(
      pathWithParams({
        path: reposPath,
        filter: filter ?? '',
        page: nextPage === 1 ? '' : nextPage.toString(),
      }),
    )
    .then(({ data }) => {
      commit(types.SET_PAGE, nextPage);
      commit(types.RECEIVE_REPOS_SUCCESS, convertObjectPropsToCamelCase(data, { deep: true }));
    })
    .catch((e) => {
      Iif (hasRedirectInError(e)) {
        redirectToUrlInError(e);
      } else if (tooManyRequests(e)) {
        createFlash({
          message: sprintf(s__('ImportProjects|%{provider} rate limit exceeded. Try again later'), {
            provider: capitalizeFirstCharacter(provider),
          }),
        });
 
        commit(types.RECEIVE_REPOS_ERROR);
      } else {
        createFlash({
          message: sprintf(s__('ImportProjects|Requesting your %{provider} repositories failed'), {
            provider,
          }),
        });
 
        commit(types.RECEIVE_REPOS_ERROR);
      }
    });
};
 
const fetchImportFactory = (importPath = isRequired()) => ({ state, commit, getters }, repoId) => {
  const { ciCdOnly } = state;
  const importTarget = getters.getImportTarget(repoId);
 
  commit(types.REQUEST_IMPORT, { repoId, importTarget });
 
  const { newName, targetNamespace } = importTarget;
  return axios
    .post(importPath, {
      repo_id: repoId,
      ci_cd_only: ciCdOnly,
      new_name: newName,
      target_namespace: targetNamespace,
    })
    .then(({ data }) => {
      commit(types.RECEIVE_IMPORT_SUCCESS, {
        importedProject: convertObjectPropsToCamelCase(data, { deep: true }),
        repoId,
      });
    })
    .catch((e) => {
      const serverErrorMessage = e?.response?.data?.errors;
      const flashMessage = serverErrorMessage
        ? sprintf(
            s__('ImportProjects|Importing the project failed: %{reason}'),
            {
              reason: serverErrorMessage,
            },
            false,
          )
        : s__('ImportProjects|Importing the project failed');
 
      createFlash({
        message: flashMessage,
      });
 
      commit(types.RECEIVE_IMPORT_ERROR, repoId);
    });
};
 
export const fetchJobsFactory = (jobsPath = isRequired()) => ({ state, commit, dispatch }) => {
  Iif (eTagPoll) {
    stopJobsPolling();
    clearJobsEtagPoll();
  }
 
  eTagPoll = new Poll({
    resource: {
      fetchJobs: () => axios.get(pathWithParams({ path: jobsPath, filter: state.filter })),
    },
    method: 'fetchJobs',
    successCallback: ({ data }) =>
      commit(types.RECEIVE_JOBS_SUCCESS, convertObjectPropsToCamelCase(data, { deep: true })),
    errorCallback: (e) => {
      if (hasRedirectInError(e)) {
        redirectToUrlInError(e);
      } else {
        createFlash({
          message: s__('ImportProjects|Update of imported projects with realtime changes failed'),
        });
      }
    },
  });
 
  Eif (!Visibility.hidden()) {
    eTagPoll.makeRequest();
  }
 
  Visibility.change(() => {
    if (!Visibility.hidden()) {
      dispatch('restartJobsPolling');
    } else {
      dispatch('stopJobsPolling');
    }
  });
};
 
const fetchNamespacesFactory = (namespacesPath = isRequired()) => ({ commit }) => {
  commit(types.REQUEST_NAMESPACES);
  axios
    .get(namespacesPath)
    .then(({ data }) =>
      commit(types.RECEIVE_NAMESPACES_SUCCESS, convertObjectPropsToCamelCase(data, { deep: true })),
    )
    .catch(() => {
      createFlash({
        message: s__('ImportProjects|Requesting namespaces failed'),
      });
 
      commit(types.RECEIVE_NAMESPACES_ERROR);
    });
};
 
const setFilter = ({ commit, dispatch }, filter) => {
  commit(types.SET_FILTER, filter);
 
  return dispatch('fetchRepos');
};
 
export default ({ endpoints = isRequired() }) => ({
  clearJobsEtagPoll,
  stopJobsPolling,
  restartJobsPolling,
  setFilter,
  setImportTarget,
  importAll,
  fetchRepos: fetchReposFactory({ reposPath: endpoints.reposPath }),
  fetchImport: fetchImportFactory(endpoints.importPath),
  fetchJobs: fetchJobsFactory(endpoints.jobsPath),
  fetchNamespaces: fetchNamespacesFactory(endpoints.namespacesPath),
});