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';
import csrf from './csrf';
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
2018-12-13 13:39:08 +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;
});
// Remove the global counter
2018-12-13 13:39:08 +05:30
axios.interceptors.response.use(
2019-12-04 20:38:33 +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
},
2019-12-04 20:38:33 +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
let isUserNavigating = false;
window.addEventListener('beforeunload', () => {
isUserNavigating = true;
});
// Ignore AJAX errors caused by requests
// being cancelled due to browser navigation
const { gon } = window;
const featureFlagEnabled = gon && gon.features && gon.features.suppressAjaxNavigationErrors;
axios.interceptors.response.use(
response => response,
err => suppressAjaxErrorsDuringNavigation(err, isUserNavigating, featureFlagEnabled),
);
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;