blob: 63fd75cbdac85ba002001a57364608e7f36a01fe [file] [log] [blame]
Derick Montaguefded0d12019-12-11 06:16:40 -06001import Axios from 'axios';
Derick Montague126eaab2019-12-23 13:33:52 -06002import router from '../router';
Yoshie Muranaka68069e12020-05-15 08:06:46 -07003import store from '@/store';
Yoshie Muranaka74c24f12019-12-03 10:45:46 -08004
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -08005const api = Axios.create({
6 withCredentials: true
7});
Yoshie Muranaka74c24f12019-12-03 10:45:46 -08008
Derick Montague227c41a2019-12-20 17:08:59 -06009api.interceptors.response.use(undefined, error => {
10 let response = error.response;
Derick Montague126eaab2019-12-23 13:33:52 -060011
Derick Montague227c41a2019-12-20 17:08:59 -060012 // TODO: Provide user with a notification and way to keep system active
13 if (response.status == 401) {
Derick Montague676f2fc2019-12-23 20:53:49 -060014 if (response.config.url != '/login') {
15 window.location = '/login';
Yoshie Muranaka68069e12020-05-15 08:06:46 -070016 // Commit logout to remove XSRF-TOKEN cookie
17 store.commit('authentication/logout');
Derick Montague676f2fc2019-12-23 20:53:49 -060018 }
Derick Montague227c41a2019-12-20 17:08:59 -060019 }
Derick Montague126eaab2019-12-23 13:33:52 -060020
21 if (response.status == 403) {
Yoshie Muranakac60d2e12020-06-01 09:44:23 -070022 if (router.history.current.name === 'unauthorized') {
23 // Check if current router location is unauthorized
24 // to avoid NavigationDuplicated errors.
25 // The router throws an error if trying to push to the
26 // same/current router location.
27 return;
28 }
Derick Montague126eaab2019-12-23 13:33:52 -060029 router.push({ name: 'unauthorized' });
30 }
Derick Montague676f2fc2019-12-23 20:53:49 -060031
32 return Promise.reject(error);
Derick Montague227c41a2019-12-20 17:08:59 -060033});
34
Yoshie Muranaka74c24f12019-12-03 10:45:46 -080035export default {
36 get(path) {
37 return api.get(path);
38 },
39 delete(path, payload) {
40 return api.delete(path, payload);
41 },
Yoshie Muranaka37393812020-03-24 15:25:24 -070042 post(path, payload, config) {
43 return api.post(path, payload, config);
Yoshie Muranaka74c24f12019-12-03 10:45:46 -080044 },
45 patch(path, payload) {
46 return api.patch(path, payload);
47 },
48 put(path, payload) {
49 return api.put(path, payload);
50 },
51 all(promises) {
52 return Axios.all(promises);
Yoshie Muranaka183c2752020-02-12 11:30:49 -080053 },
54 spread(callback) {
55 return Axios.spread(callback);
Yoshie Muranakadc04feb2019-12-04 08:41:22 -080056 }
Yoshie Muranaka74c24f12019-12-03 10:45:46 -080057};
Yoshie Muranakabe3af332020-05-11 08:23:04 -070058
59export const getResponseCount = responses => {
60 let successCount = 0;
61 let errorCount = 0;
62
63 responses.forEach(response => {
64 if (response instanceof Error) errorCount++;
65 else successCount++;
66 });
67
68 return {
69 successCount,
70 errorCount
71 };
72};