xref: /openbmc/webui-vue/src/store/api.js (revision a88f7529)
1import Axios from 'axios';
2import router from '../router';
3import store from '@/store';
4
5const api = Axios.create({
6  withCredentials: true
7});
8
9api.interceptors.response.use(undefined, error => {
10  let response = error.response;
11
12  // TODO: Provide user with a notification and way to keep system active
13  if (response.status == 401) {
14    if (response.config.url != '/login') {
15      window.location = '/login';
16      // Commit logout to remove XSRF-TOKEN cookie
17      store.commit('authentication/logout');
18    }
19  }
20
21  if (response.status == 403) {
22    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    }
29    router.push({ name: 'unauthorized' });
30  }
31
32  return Promise.reject(error);
33});
34
35export default {
36  get(path) {
37    return api.get(path);
38  },
39  delete(path, payload) {
40    return api.delete(path, payload);
41  },
42  post(path, payload, config) {
43    return api.post(path, payload, config);
44  },
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);
53  },
54  spread(callback) {
55    return Axios.spread(callback);
56  }
57};
58
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};
73