forked from wednesday-solutions/react-native-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiUtils.js
More file actions
54 lines (52 loc) · 1.44 KB
/
apiUtils.js
File metadata and controls
54 lines (52 loc) · 1.44 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
/* eslint-disable sonarjs/no-small-switch */
/* eslint-disable fp/no-mutating-assign */
import { create } from 'apisauce';
import mapKeysDeep from 'map-keys-deep';
import camelCase from 'lodash/camelCase';
import snakeCase from 'lodash/snakeCase';
import { Config } from '@app/config/index';
import get from 'lodash/get';
export const apiClients = {
configApi: null,
default: null
};
export const getApiClient = (type = 'configApi') => apiClients[type];
export const generateApiClient = (type = 'configApi') => {
switch (type) {
case 'configApi':
Object.assign(apiClients, {
[type]: createApiClientWithTransForm(Config.API_URL)
});
return get(apiClients, type);
default:
Object.assign(apiClients, {
default: createApiClientWithTransForm(Config.API_URL)
});
return apiClients.default;
}
};
export const createApiClientWithTransForm = baseURL => {
const api = create({
baseURL,
headers: { 'Content-Type': 'application/json' }
});
api.addResponseTransform(response => {
const { ok, data } = response;
if (ok && data) {
Object.assign(response, {
data: mapKeysDeep(data, keys => camelCase(keys))
});
}
return response;
});
api.addRequestTransform(request => {
const { data } = request;
if (data) {
Object.assign(request, {
data: mapKeysDeep(data, keys => snakeCase(keys))
});
}
return request;
});
return api;
};