debian-mirror-gitlab/app/assets/javascripts/lib/utils/axios_utils.js

52 lines
1.6 KiB
JavaScript
Raw Normal View History

2018-03-17 18:26:18 +05:30
import axios from 'axios';
2021-09-30 23:02:18 +05:30
import { registerCaptchaModalInterceptor } from '~/captcha/captcha_modal_axios_interceptor';
2021-03-11 19:13:27 +05:30
import setupAxiosStartupCalls from './axios_startup_calls';
2018-03-17 18:26:18 +05:30
import csrf from './csrf';
2021-11-18 22:05:49 +05:30
import { isNavigatingAway } from './is_navigating_away';
2019-12-21 20:55:43 +05:30
import suppressAjaxErrorsDuringNavigation from './suppress_ajax_errors_during_navigation';
2018-03-17 18:26:18 +05:30
axios.defaults.headers.common[csrf.headerKey] = csrf.token;
// Used by Rails to check if it is a valid XHR request
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// Maintain a global counter for active requests
// see: spec/support/wait_for_requests.rb
2021-03-08 18:12:59 +05:30
axios.interceptors.request.use((config) => {
2019-12-21 20:55:43 +05:30
window.pendingRequests = window.pendingRequests || 0;
window.pendingRequests += 1;
2018-03-17 18:26:18 +05:30
return config;
});
2020-07-28 23:09:34 +05:30
setupAxiosStartupCalls(axios);
2018-03-17 18:26:18 +05:30
// Remove the global counter
2018-12-13 13:39:08 +05:30
axios.interceptors.response.use(
2021-03-08 18:12:59 +05:30
(response) => {
2019-12-21 20:55:43 +05:30
window.pendingRequests -= 1;
2019-12-04 20:38:33 +05:30
return response;
2018-12-13 13:39:08 +05:30
},
2021-03-08 18:12:59 +05:30
(err) => {
2019-12-21 20:55:43 +05:30
window.pendingRequests -= 1;
2019-12-04 20:38:33 +05:30
return Promise.reject(err);
2018-12-13 13:39:08 +05:30
},
);
2018-03-17 18:26:18 +05:30
2019-12-21 20:55:43 +05:30
// Ignore AJAX errors caused by requests
// being cancelled due to browser navigation
axios.interceptors.response.use(
2021-03-08 18:12:59 +05:30
(response) => response,
2021-11-18 22:05:49 +05:30
(err) => suppressAjaxErrorsDuringNavigation(err, isNavigatingAway()),
2019-12-21 20:55:43 +05:30
);
2021-09-30 23:02:18 +05:30
registerCaptchaModalInterceptor(axios);
2018-03-17 18:26:18 +05:30
export default axios;
/**
* @return The adapter that axios uses for dispatching requests. This may be overwritten in tests.
*
* @see https://github.com/axios/axios/tree/master/lib/adapters
* @see https://github.com/ctimmerm/axios-mock-adapter/blob/v1.12.0/src/index.js#L39
*/
export const getDefaultAdapter = () => axios.defaults.adapter;