blob: 77d9432942fd2bb5858cf93ffca5e550bacb418d [file] [log] [blame]
Derick Montaguefded0d12019-12-11 06:16:40 -06001import Axios from 'axios';
Yoshie Muranaka8263d852020-10-16 07:58:06 -07002//Do not change store import.
3//Exact match alias set to support
4//dotenv customizations.
Yoshie Muranaka816d9472020-09-03 11:19:28 -07005import store from '../store';
Yoshie Muranaka74c24f12019-12-03 10:45:46 -08006
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -08007const api = Axios.create({
8 withCredentials: true
9});
Yoshie Muranaka74c24f12019-12-03 10:45:46 -080010
Derick Montague227c41a2019-12-20 17:08:59 -060011api.interceptors.response.use(undefined, error => {
12 let response = error.response;
Derick Montague126eaab2019-12-23 13:33:52 -060013
Derick Montague227c41a2019-12-20 17:08:59 -060014 // TODO: Provide user with a notification and way to keep system active
15 if (response.status == 401) {
Derick Montague676f2fc2019-12-23 20:53:49 -060016 if (response.config.url != '/login') {
17 window.location = '/login';
Yoshie Muranaka68069e12020-05-15 08:06:46 -070018 // Commit logout to remove XSRF-TOKEN cookie
19 store.commit('authentication/logout');
Derick Montague676f2fc2019-12-23 20:53:49 -060020 }
Derick Montague227c41a2019-12-20 17:08:59 -060021 }
Derick Montague126eaab2019-12-23 13:33:52 -060022
23 if (response.status == 403) {
Sukanya Pandeydd6aa0a2020-10-08 20:47:39 +053024 // Check if action is unauthorized.
25 // Toast error message will appear on screen
26 // when the action is unauthorized.
27 store.commit('global/setUnauthorized');
Derick Montague126eaab2019-12-23 13:33:52 -060028 }
Derick Montague676f2fc2019-12-23 20:53:49 -060029
30 return Promise.reject(error);
Derick Montague227c41a2019-12-20 17:08:59 -060031});
32
Yoshie Muranaka74c24f12019-12-03 10:45:46 -080033export default {
34 get(path) {
35 return api.get(path);
36 },
37 delete(path, payload) {
38 return api.delete(path, payload);
39 },
Yoshie Muranaka37393812020-03-24 15:25:24 -070040 post(path, payload, config) {
41 return api.post(path, payload, config);
Yoshie Muranaka74c24f12019-12-03 10:45:46 -080042 },
43 patch(path, payload) {
44 return api.patch(path, payload);
45 },
46 put(path, payload) {
47 return api.put(path, payload);
48 },
49 all(promises) {
50 return Axios.all(promises);
Yoshie Muranaka183c2752020-02-12 11:30:49 -080051 },
52 spread(callback) {
53 return Axios.spread(callback);
Yoshie Muranakadc04feb2019-12-04 08:41:22 -080054 }
Yoshie Muranaka74c24f12019-12-03 10:45:46 -080055};
Yoshie Muranakabe3af332020-05-11 08:23:04 -070056
57export const getResponseCount = responses => {
58 let successCount = 0;
59 let errorCount = 0;
60
61 responses.forEach(response => {
62 if (response instanceof Error) errorCount++;
63 else successCount++;
64 });
65
66 return {
67 successCount,
68 errorCount
69 };
70};