2017-11-02 10:24:24 -04:00
|
|
|
import axios from 'axios';
|
2021-02-14 13:09:20 -05:00
|
|
|
import setupAxiosStartupCalls from './axios_startup_calls';
|
2017-11-02 10:24:24 -04:00
|
|
|
import csrf from './csrf';
|
2019-09-27 14:06:20 -04:00
|
|
|
import suppressAjaxErrorsDuringNavigation from './suppress_ajax_errors_during_navigation';
|
2017-11-02 10:24:24 -04:00
|
|
|
|
2017-11-20 04:57:08 -05:00
|
|
|
axios.defaults.headers.common[csrf.headerKey] = csrf.token;
|
2017-12-15 16:29:44 -05:00
|
|
|
// Used by Rails to check if it is a valid XHR request
|
|
|
|
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
|
2017-11-20 04:57:08 -05:00
|
|
|
|
|
|
|
// Maintain a global counter for active requests
|
|
|
|
// see: spec/support/wait_for_requests.rb
|
2020-12-23 19:10:25 -05:00
|
|
|
axios.interceptors.request.use((config) => {
|
2019-09-19 07:50:12 -04:00
|
|
|
window.pendingRequests = window.pendingRequests || 0;
|
|
|
|
window.pendingRequests += 1;
|
2017-11-20 04:57:08 -05:00
|
|
|
return config;
|
|
|
|
});
|
|
|
|
|
2020-06-19 14:08:39 -04:00
|
|
|
setupAxiosStartupCalls(axios);
|
|
|
|
|
2017-11-20 04:57:08 -05:00
|
|
|
// Remove the global counter
|
2018-10-10 02:25:43 -04:00
|
|
|
axios.interceptors.response.use(
|
2020-12-23 19:10:25 -05:00
|
|
|
(response) => {
|
2019-09-19 07:50:12 -04:00
|
|
|
window.pendingRequests -= 1;
|
2019-09-05 08:56:17 -04:00
|
|
|
return response;
|
2018-10-10 02:25:43 -04:00
|
|
|
},
|
2020-12-23 19:10:25 -05:00
|
|
|
(err) => {
|
2019-09-19 07:50:12 -04:00
|
|
|
window.pendingRequests -= 1;
|
2019-09-05 08:56:17 -04:00
|
|
|
return Promise.reject(err);
|
2018-10-10 02:25:43 -04:00
|
|
|
},
|
|
|
|
);
|
2017-11-20 04:57:08 -05:00
|
|
|
|
2019-09-27 14:06:20 -04:00
|
|
|
let isUserNavigating = false;
|
|
|
|
window.addEventListener('beforeunload', () => {
|
|
|
|
isUserNavigating = true;
|
|
|
|
});
|
|
|
|
|
|
|
|
// Ignore AJAX errors caused by requests
|
|
|
|
// being cancelled due to browser navigation
|
|
|
|
axios.interceptors.response.use(
|
2020-12-23 19:10:25 -05:00
|
|
|
(response) => response,
|
|
|
|
(err) => suppressAjaxErrorsDuringNavigation(err, isUserNavigating),
|
2019-09-27 14:06:20 -04:00
|
|
|
);
|
|
|
|
|
2017-11-20 04:57:08 -05:00
|
|
|
export default axios;
|
2018-01-23 14:16:26 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @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;
|