-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathApiClient.ts
More file actions
99 lines (88 loc) · 1.96 KB
/
ApiClient.ts
File metadata and controls
99 lines (88 loc) · 1.96 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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import axios from 'axios';
class ApiClient {
headers: Record<string, string>;
settings: { baseURL: string };
constructor({
apiUrl,
headers = {},
}: {
apiUrl: string;
headers?: Record<string, string>;
}) {
this.headers = headers;
this.settings = {
baseURL: apiUrl,
};
}
setHeaders = (headers: Record<string, string>) => {
this.headers = { ...this.headers, ...headers };
};
async get(endpoint, params = {}, opts = {}) {
return await this.send({
method: 'get',
endpoint: endpoint,
params: params,
...opts,
});
}
async post(endpoint, payload = {}, opts = {}) {
return await this.send({
method: 'post',
endpoint: endpoint,
payload: payload,
...opts,
});
}
async put(endpoint, payload = {}, opts = {}) {
return await this.send({
method: 'put',
endpoint: endpoint,
payload: payload,
...opts,
});
}
async patch(endpoint, payload = {}, opts = {}) {
return await this.send({
method: 'patch',
endpoint: endpoint,
payload: payload,
...opts,
});
}
async delete(endpoint, payload = {}, opts = {}) {
return await this.send({
method: 'delete',
endpoint: endpoint,
payload: payload,
...opts,
});
}
async send(request) {
const {
method = 'get',
endpoint,
payload = {},
headers = {},
params,
} = request;
try {
const response = await axios({
method,
headers: { ...this.headers, ...headers },
params,
url: endpoint,
data: payload,
...this.settings,
});
return response.data;
} catch (error) {
// TODO: We should throw the error directly from here.
// throw new error();
// However, by doing this may change the behavior of the error handling of APIs using this ApiClient.
return {
error,
};
}
}
}
export default ApiClient;