-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
70 lines (60 loc) · 1.91 KB
/
Copy pathapi.js
File metadata and controls
70 lines (60 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import axios from 'axios';
import store from '../store';
import { BACKEND_URL, REQUEST_TIMEOUT_MS } from '../config/runtime';
import { setServerOffline, setServerOnline } from '../actions/serverActions';
import { SERVER_STATUS_OFFLINE, SERVER_STATUS_ONLINE } from '../constants/serverConstants';
const api = axios.create({
baseURL: BACKEND_URL,
timeout: REQUEST_TIMEOUT_MS,
headers: {
'Content-Type': 'application/json',
},
});
api.interceptors.request.use(
(config) => {
const state = store.getState();
const token = state.userLogin?.userInfo?.token;
if (!config.baseURL) {
config.baseURL = BACKEND_URL;
}
if (token && !config.headers.Authorization) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// --- RESPONSE INTERCEPTOR (Error Handling) ---
api.interceptors.response.use(
(response) => {
const { serverStatus } = store.getState();
if (serverStatus?.status !== SERVER_STATUS_ONLINE) {
store.dispatch(setServerOnline());
}
return response;
},
(error) => {
if (error.code === 'ECONNABORTED' || error.message?.toLowerCase().includes('timeout')) {
console.error('API timeout at', BACKEND_URL);
} else if (error.request && !error.response && error.code !== 'ERR_CANCELED') {
const { serverStatus } = store.getState();
if (serverStatus?.status !== SERVER_STATUS_OFFLINE) {
console.error('Network Error: Server unreachable at', BACKEND_URL);
store.dispatch(setServerOffline());
}
} else if (!error.response) {
console.error('API Setup Error:', error.message);
}
return Promise.reject(error);
}
);
export const buildRequestConfig = ({ token, headers = {}, ...config } = {}) => ({
...config,
headers: {
...headers,
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
});
export default api;