-
Notifications
You must be signed in to change notification settings - Fork 2k
/
api.js
67 lines (62 loc) · 1.89 KB
/
api.js
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
import axios from 'axios';
import history from 'browserHistory';
import toast from 'shared/utils/toast';
import { objectToQueryString } from 'shared/utils/url';
import { getStoredAuthToken, removeStoredAuthToken } from 'shared/utils/authToken';
const defaults = {
baseURL: process.env.API_URL || 'http://localhost:3000',
headers: () => ({
'Content-Type': 'application/json',
Authorization: getStoredAuthToken() ? `Bearer ${getStoredAuthToken()}` : undefined,
}),
error: {
code: 'INTERNAL_ERROR',
message: 'Something went wrong. Please check your internet connection or contact our support.',
status: 503,
data: {},
},
};
const api = (method, url, variables) =>
new Promise((resolve, reject) => {
axios({
url: `${defaults.baseURL}${url}`,
method,
headers: defaults.headers(),
params: method === 'get' ? variables : undefined,
data: method !== 'get' ? variables : undefined,
paramsSerializer: objectToQueryString,
}).then(
response => {
resolve(response.data);
},
error => {
if (error.response) {
if (error.response.data.error.code === 'INVALID_TOKEN') {
removeStoredAuthToken();
history.push('/authenticate');
} else {
reject(error.response.data.error);
}
} else {
reject(defaults.error);
}
},
);
});
const optimisticUpdate = async (url, { updatedFields, currentFields, setLocalData }) => {
try {
setLocalData(updatedFields);
await api('put', url, updatedFields);
} catch (error) {
setLocalData(currentFields);
toast.error(error);
}
};
export default {
get: (...args) => api('get', ...args),
post: (...args) => api('post', ...args),
put: (...args) => api('put', ...args),
patch: (...args) => api('patch', ...args),
delete: (...args) => api('delete', ...args),
optimisticUpdate,
};