forked from wednesday-solutions/react-graphql-ts-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiUtils.ts
42 lines (37 loc) · 1.16 KB
/
apiUtils.ts
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
import { ApisauceInstance, create } from 'apisauce';
import snakeCase from 'lodash-es/snakeCase';
import camelCase from 'lodash-es/camelCase';
import { mapKeysDeep } from './index';
const apiClients: Record<string, ApisauceInstance> = {};
export const getApiClient = (type = 'spacex') => apiClients[type];
export const generateApiClient = (type = 'spacex') => {
switch (type) {
case 'spacex':
apiClients[type] = createApiClientWithTransForm(process.env.SPACEX_URL!);
return apiClients[type];
default:
apiClients.default = createApiClientWithTransForm(process.env.SPACEX_URL!);
return apiClients.default;
}
};
export const createApiClientWithTransForm = (baseURL: string) => {
const api = create({
baseURL,
headers: { 'Content-Type': 'application/json' }
});
api.addResponseTransform((response) => {
const { ok, data } = response;
if (ok && data) {
response.data = mapKeysDeep(data, camelCase);
}
return response;
});
api.addRequestTransform((request) => {
const { data } = request;
if (data) {
request.data = mapKeysDeep(data, snakeCase);
}
return request;
});
return api;
};