All files / ee/app/assets/javascripts/dependencies/store/modules/list actions.js

98.01% Statements 99/101
88.57% Branches 31/35
97.14% Functions 34/35
98.96% Lines 96/97

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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273                                                10x 1x   10x 1x   10x   10x   10x   10x 3x                 10x 2x           10x 5x 5x 3x   2x     10x 5x 5x 5x 15x         5x             10x 1x   10x 5x           5x 5x                 5x     10x 6x 1x     5x   5x     3x 2x   1x       3x   3x   3x       3x       10x 1x 1x     10x 1x 1x     10x 4x 1x     3x   3x     2x 1x   1x       2x 2x           10x 3x         10x 4x   3x 3x             1x         4x       10x 2x         2x 4x       4x 1x     3x   1x 3x   1x     3x     2x     10x   3x 1x     2x   2x     2x   1x     1x     1x   1x       2x       10x 3x 1x     2x   2x             1x     1x         2x      
import { createAlert } from '~/alert';
import axios from '~/lib/utils/axios_utils';
import {
  convertObjectPropsToCamelCase,
  normalizeHeaders,
  parseIntPagination,
} from '~/lib/utils/common_utils';
import { NAMESPACE_ORGANIZATION } from 'ee/dependencies/constants';
import { __, sprintf } from '~/locale';
import pollUntilComplete from '~/lib/utils/poll_until_complete';
import download from '~/lib/utils/downloader';
import { HTTP_STATUS_CREATED } from '~/lib/utils/http_status';
import {
  DEPENDENCIES_CSV_FILENAME,
  DEPENDENCIES_FILENAME,
  FETCH_ERROR_MESSAGE,
  FETCH_ERROR_MESSAGE_WITH_DETAILS,
  FETCH_EXPORT_ERROR_MESSAGE,
  LICENSES_FETCH_ERROR_MESSAGE,
  VULNERABILITIES_FETCH_ERROR_MESSAGE,
} from './constants';
import * as types from './mutation_types';
import { isValidResponse } from './utils';
 
export const setDependenciesEndpoint = ({ commit }, endpoint) =>
  commit(types.SET_DEPENDENCIES_ENDPOINT, endpoint);
 
export const setExportDependenciesEndpoint = ({ commit }, payload) =>
  commit(types.SET_EXPORT_DEPENDENCIES_ENDPOINT, payload);
 
export const setNamespaceType = ({ commit }, payload) => commit(types.SET_NAMESPACE_TYPE, payload);
 
export const setInitialState = ({ commit }, payload) => commit(types.SET_INITIAL_STATE, payload);
 
export const requestDependencies = ({ commit }) => commit(types.REQUEST_DEPENDENCIES);
 
const parseCursorPagination = (headers) => {
  return {
    type: headers['X-PAGE-TYPE'],
    endCursor: headers['X-NEXT-PAGE'],
    hasNextPage: headers['X-NEXT-PAGE'] !== '',
    hasPreviousPage: headers['X-PREV-PAGE'] !== '',
    startCursor: headers['X-PREV-PAGE'],
  };
};
 
const parseOffsetPagination = (headers) => {
  return {
    ...parseIntPagination(headers),
    type: 'offset',
  };
};
 
const parsePagination = (headers) => {
  const paginateWithCursor = headers['X-PAGE-TYPE'] === 'cursor';
  if (paginateWithCursor) {
    return parseCursorPagination(headers);
  }
  return parseOffsetPagination(headers);
};
 
export const receiveDependenciesSuccess = ({ commit }, { headers, data }) => {
  const pageInfo = parsePagination(normalizeHeaders(headers));
  const { dependencies, report: reportInfo } = data;
  const convertedDependencies = dependencies.map((item) =>
    convertObjectPropsToCamelCase(item, {
      deep: true,
    }),
  );
 
  commit(types.RECEIVE_DEPENDENCIES_SUCCESS, {
    dependencies: convertedDependencies,
    reportInfo,
    pageInfo,
  });
};
 
export const receiveDependenciesError = ({ commit }, error) =>
  commit(types.RECEIVE_DEPENDENCIES_ERROR, error);
 
const queryParametersFor = (state, params) => {
  Iif (state.pageInfo.type === 'cursor') {
    return {
      cursor: params.cursor,
    };
  }
 
  const { searchFilterParameters } = state;
  const queryParams = {
    sort_by: state.sortField,
    sort: state.sortOrder,
    page: state.pageInfo.page || 1,
    filter: state.filter,
    ...searchFilterParameters,
    ...params,
  };
 
  return queryParams;
};
 
export const fetchDependencies = ({ state, dispatch }, params) => {
  if (!state.endpoint) {
    return;
  }
 
  dispatch('requestDependencies');
 
  axios
    .get(state.endpoint, { params: queryParametersFor(state, params) })
    .then((response) => {
      if (isValidResponse(response)) {
        dispatch('receiveDependenciesSuccess', response);
      } else {
        throw new Error(__('Invalid server response'));
      }
    })
    .catch((error) => {
      dispatch('receiveDependenciesError', error);
 
      const errorDetails = error?.response?.data?.message;
 
      const message = errorDetails
        ? sprintf(FETCH_ERROR_MESSAGE_WITH_DETAILS, { errorDetails })
        : FETCH_ERROR_MESSAGE;
 
      createAlert({ message });
    });
};
 
export const setSortField = ({ commit, dispatch }, id) => {
  commit(types.SET_SORT_FIELD, id);
  dispatch('fetchDependencies', { page: 1 });
};
 
export const toggleSortOrder = ({ commit, dispatch }) => {
  commit(types.TOGGLE_SORT_ORDER);
  dispatch('fetchDependencies', { page: 1 });
};
 
export const fetchExport = ({ state, commit, dispatch }) => {
  if (!state.exportEndpoint) {
    return;
  }
 
  commit(types.SET_FETCHING_IN_PROGRESS, true);
 
  axios
    .post(state.exportEndpoint)
    .then((response) => {
      if (response?.status === HTTP_STATUS_CREATED) {
        dispatch('downloadExport', response?.data?.self);
      } else {
        throw new Error(__('Invalid server response'));
      }
    })
    .catch(() => {
      commit(types.SET_FETCHING_IN_PROGRESS, false);
      createAlert({
        message: FETCH_EXPORT_ERROR_MESSAGE,
      });
    });
};
 
const exportFilenameFor = (namespaceType) => {
  return namespaceType === NAMESPACE_ORGANIZATION
    ? DEPENDENCIES_CSV_FILENAME
    : DEPENDENCIES_FILENAME;
};
 
export const downloadExport = ({ state, commit }, dependencyListExportEndpoint) => {
  pollUntilComplete(dependencyListExportEndpoint)
    .then((response) => {
      Eif (response.data?.has_finished) {
        download({
          url: response.data?.download,
          fileName: exportFilenameFor(state?.namespaceType),
        });
      }
    })
    .catch(() => {
      createAlert({
        message: FETCH_EXPORT_ERROR_MESSAGE,
      });
    })
    .finally(() => {
      commit(types.SET_FETCHING_IN_PROGRESS, false);
    });
};
 
export const setSearchFilterParameters = ({ state, commit }, searchFilters = []) => {
  const searchFilterParameters = {};
 
  // populate the searchFilterParameters object with the data from the search filters. For example:
  // given filters: [{ type: 'licenses', value: { data: ['MIT', 'GNU'] } }, { type: 'project', value: { data: ['GitLab'] } }
  // will result in the parameters: { licenses: ['MIT', 'GNU'], project: ['GitLab'] }
  searchFilters.forEach((searchFilter) => {
    let filterData = searchFilter.value.data;
 
    // If a user types to filter available options the filter data will be a string and we just ignore it
    // as filters can only be applied via selecting an option from the dropdown
    if (!Array.isArray(filterData) || !filterData.length) {
      return;
    }
 
    if (searchFilter.type === 'licenses') {
      // for the license filter we display the license name in the UI, but want to send the spdx-identifier to the API
      const getSpdxIdentifier = (licenseName) =>
        state.licenses.find(({ name }) => name === licenseName)?.spdxIdentifier || [];
 
      filterData = filterData.flatMap(getSpdxIdentifier);
    }
 
    searchFilterParameters[searchFilter.type] = filterData;
  });
 
  commit(types.SET_SEARCH_FILTER_PARAMETERS, searchFilterParameters);
};
 
export const fetchLicenses = async ({ commit, state }, licensesEndpoint) => {
  // if there are already licenses there is no need to re-fetch, as they are a static list
  if (state.licenses.length || !licensesEndpoint) {
    return;
  }
 
  commit(types.SET_FETCHING_LICENSES_IN_PROGRESS, true);
 
  try {
    const {
      data: { licenses },
    } = await axios.get(licensesEndpoint);
 
    const camelCasedLicensesWithId = licenses.map((license, index) =>
      // we currently don't get the id from the API, so we need to add it manually
      // this will be removed once https://gitlab.com/gitlab-org/gitlab/-/issues/439886 has been implemented
      convertObjectPropsToCamelCase({ ...license, id: index }, { deep: true }),
    );
 
    commit(types.SET_LICENSES, camelCasedLicensesWithId);
  } catch (e) {
    createAlert({
      message: LICENSES_FETCH_ERROR_MESSAGE,
    });
  } finally {
    commit(types.SET_FETCHING_LICENSES_IN_PROGRESS, false);
  }
};
 
export const fetchVulnerabilities = ({ commit }, { item, vulnerabilitiesEndpoint }) => {
  if (!vulnerabilitiesEndpoint) {
    return;
  }
 
  commit(types.TOGGLE_VULNERABILITY_ITEM_LOADING, item);
 
  axios
    .get(vulnerabilitiesEndpoint, {
      params: {
        id: item.occurrenceId,
      },
    })
    .then(({ data }) => {
      commit(types.SET_VULNERABILITIES, data);
    })
    .catch(() => {
      createAlert({
        message: VULNERABILITIES_FETCH_ERROR_MESSAGE,
      });
    })
    .finally(() => {
      commit(types.TOGGLE_VULNERABILITY_ITEM_LOADING, item);
    });
};