| 65 | } |
| 66 | |
| 67 | export default class ApiClient { |
| 68 | instance: AxiosInstance; |
| 69 | |
| 70 | constructor({ |
| 71 | baseURL = '/', |
| 72 | customInterceptor, |
| 73 | }: { baseURL?: string; customInterceptor?: any } = {}) { |
| 74 | this.instance = axios.create({ |
| 75 | baseURL, |
| 76 | }); |
| 77 | this.instance.interceptors.request.use(async (request) => { |
| 78 | request.headers = { |
| 79 | ...request.headers, |
| 80 | 'Content-Type': 'application/json', |
| 81 | Accept: 'application/json', |
| 82 | }; |
| 83 | return request; |
| 84 | }); |
| 85 | customInterceptor && |
| 86 | this.instance.interceptors.request.use(customInterceptor); |
| 87 | } |
| 88 | |
| 89 | catchError = (e: { response: any }) => { |
| 90 | const { response } = e; |
| 91 | if (!response || response.status >= 500) { |
| 92 | const error = new HttpError( |
| 93 | 500, |
| 94 | 'InternalServerError', |
| 95 | 'An internal error occurred. Please try again' |
| 96 | ); |
| 97 | console.error(error); |
| 98 | throw error; |
| 99 | } else { |
| 100 | const error = new HttpError( |
| 101 | response.status, |
| 102 | response.statusText, |
| 103 | response.data?.message |
| 104 | ); |
| 105 | console.error(error); |
| 106 | throw error; |
| 107 | } |
| 108 | }; |
| 109 | |
| 110 | get = <T>(path: string) => |
| 111 | this.instance |
| 112 | .get<T>(path) |
| 113 | .then((res) => res.data) |
| 114 | .catch(this.catchError); |
| 115 | |
| 116 | post = <T>(path: string, data = {}) => |
| 117 | this.instance |
| 118 | .post<T>(path, data) |
| 119 | .then((res) => res.data) |
| 120 | .catch(this.catchError); |
| 121 | |
| 122 | postWithOptions = <T>(path: string, data = {}, options: AxiosRequestConfig) => |
| 123 | this.instance |
| 124 | .post<T>(path, data, options) |