-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
36 lines (30 loc) · 862 Bytes
/
api.ts
File metadata and controls
36 lines (30 loc) · 862 Bytes
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
import axios, { AxiosError, AxiosResponse } from 'axios';
import urlJoin from 'url-join';
import { API_STATUS } from '../constants/api';
const baseURL = process.env.REACT_APP_API_ENDPOINT || '';
const linkApi = (resource: string) => {
return urlJoin(baseURL, resource);
};
const handleError = (error: AxiosError) => {
if (!error.response?.status || [API_STATUS.HTTP_500_SERVER].includes(error.response?.status)) {
console.log(error.response);
} else {
return error.response.data;
}
};
class RestService<T, R = any> {
constructor(protected resource: string) {}
index(params?: R) {
return new Promise<AxiosResponse<T>>((resolve, rejects) => {
axios
.get<T>(linkApi(this.resource), {
params,
})
.then(resolve)
.catch((error: AxiosError) => {
rejects(handleError(error));
});
});
}
}
export default RestService;