-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathapiUtils.js
80 lines (72 loc) · 2.09 KB
/
apiUtils.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
68
69
70
71
72
73
74
75
76
77
78
79
80
/* eslint-disable sonarjs/no-small-switch */
/* eslint-disable fp/no-mutating-assign */
import axios from 'axios';
import mapKeysDeep from 'map-keys-deep';
import camelCase from 'lodash/camelCase';
import snakeCase from 'lodash/snakeCase';
import get from 'lodash/get';
import { set } from 'lodash';
import { Config } from '@app/config/index';
export const apiClients = {
configApi: null,
default: null
};
export const getApiClient = (type = 'configApi') =>
get(apiClients, type, apiClients.default);
export const generateApiClient = (type = 'configApi') => {
switch (type) {
case 'configApi':
set(apiClients, type, createApiClientWithTransForm(Config.API_URL));
return get(apiClients, type);
default:
set(apiClients, 'default', createApiClientWithTransForm(Config.API_URL));
return apiClients.default;
}
};
export const createApiClientWithTransForm = baseURL => {
try {
const api = axios.create({
baseURL,
headers: { 'Content-Type': 'application/json' }
});
// Response interceptor to transform keys to camelCase and structure response
api.interceptors.response.use(
response => {
const { data } = response;
if (data) {
const keysData = mapKeysDeep(data, keys => camelCase(keys));
return {
ok: true,
data: keysData,
error: null,
originalResponse: response
};
}
return {
ok: true,
data: response.data,
error: null,
originalResponse: response
};
},
error => ({
ok: false,
data: null,
error: error || 'Something went wrong',
originalResponse: error.response
})
);
// Request interceptor to transform keys to snake_case
api.interceptors.request.use(request => {
const { data } = request;
if (data) {
const keysData = mapKeysDeep(data, keys => snakeCase(keys));
return { ...request, data: keysData };
}
return request;
});
return api;
} catch (err) {
throw new Error(err);
}
};