generated from wednesday-solutions/react-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiUtils.js
43 lines (40 loc) · 1.15 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
import { create } from 'apisauce';
import snakeCase from 'lodash/snakeCase';
import camelCase from 'lodash/camelCase';
import { mapKeysDeep } from './index';
const apiClients = {
itunes: null,
default: null
};
export const getApiClient = (type = 'itunes') => apiClients[type];
export const generateApiClient = (type = 'itunes') => {
switch (type) {
case 'itunes':
apiClients[type] = createApiClientWithTransForm(process.env.ITUNES_URL);
return apiClients[type];
default:
apiClients.default = createApiClientWithTransForm(process.env.ITUNES_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) {
response.data = mapKeysDeep(data, (keys) => camelCase(keys));
}
return response;
});
api.addRequestTransform((request) => {
const { data } = request;
if (data) {
request.data = mapKeysDeep(data, (keys) => snakeCase(keys));
}
return request;
});
return api;
};