axios.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
  2. interface ApiService {
  3. get<T>(url: string, config?: AxiosRequestConfig): Promise<T>;
  4. post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
  5. put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
  6. delete<T>(url: string, config?: AxiosRequestConfig): Promise<T>;
  7. }
  8. type RequestOptions = {
  9. transformRequest?: AxiosRequestConfig['transformRequest'];
  10. transformResponse?: <T>(response: T, config: AxiosRequestConfig) => T;
  11. }
  12. class HttpService implements ApiService {
  13. private axiosInstance: AxiosInstance;
  14. private options?: RequestOptions;
  15. constructor(baseURL: string, options?: RequestOptions) {
  16. this.axiosInstance = axios.create({
  17. baseURL,
  18. timeout: 5000, // Set your desired timeout value
  19. });
  20. this.options = options;
  21. }
  22. get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
  23. return this.request({ url, method: 'GET', ...config })
  24. }
  25. post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
  26. return this.request({ url, method: 'POST', data, ...config })
  27. }
  28. put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
  29. return this.request({ url, method: 'PUT', data, ...config })
  30. }
  31. delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
  32. return this.request({ url, method: 'DELETE', ...config })
  33. }
  34. request<T = any>(config: AxiosRequestConfig): Promise<T> {
  35. config.headers = {
  36. ...config.headers,
  37. Authorization: localStorage.getItem('token') || '',
  38. }
  39. const { transformResponse } = this.options || {};
  40. return new Promise((resolve, reject) => {
  41. this.axiosInstance
  42. .request(config)
  43. .then((response: AxiosResponse<T>) => {
  44. if (transformResponse) {
  45. try {
  46. const res = transformResponse(response.data, config);
  47. resolve(res);
  48. }
  49. catch (e) {
  50. reject(e);
  51. }
  52. }
  53. resolve(response.data);
  54. })
  55. .catch((e: Error | AxiosError) => {
  56. reject(e);
  57. })
  58. })
  59. }
  60. }
  61. export default HttpService;