generated from wednesday-solutions/react-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiUtils.js
44 lines (41 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
44
import { create } from 'apisauce';
import snakeCase from 'lodash/snakeCase';
import camelCase from 'lodash/camelCase';
import { mapKeysDeep } from './index';
const { GITHUB_URL } = process.env;
const apiClients = {
github: null,
default: null
};
export const getApiClient = (type = 'github') => apiClients[type];
export const generateApiClient = (type = 'github') => {
switch (type) {
case 'github':
apiClients[type] = createApiClientWithTransForm(GITHUB_URL);
return apiClients[type];
default:
apiClients.default = createApiClientWithTransForm(GITHUB_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;
};