http.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
  2. import Cookies from "js-cookie";
  3. import { message } from "antd";
  4. interface ApiResponse<T> {
  5. code: number;
  6. msg: string;
  7. data: T;
  8. }
  9. interface ErrorResponse {
  10. code: number;
  11. msg: string;
  12. msgZh: string;
  13. }
  14. export interface ProcessedResponse<T> {
  15. data: T;
  16. error: null | Pick<ErrorResponse, "msg" | "msgZh">;
  17. }
  18. interface CustomAxiosInstance
  19. extends Omit<AxiosInstance, "get" | "post" | "put" | "delete"> {
  20. get<T, R = AxiosResponse<ProcessedResponse<T>>>(
  21. url: string,
  22. config?: AxiosRequestConfig
  23. ): Promise<R>;
  24. post<T, R = AxiosResponse<ProcessedResponse<T>>>(
  25. url: string,
  26. data?: unknown,
  27. config?: AxiosRequestConfig
  28. ): Promise<R>;
  29. put<T, R = AxiosResponse<ProcessedResponse<T>>>(
  30. url: string,
  31. data?: unknown,
  32. config?: AxiosRequestConfig
  33. ): Promise<R>;
  34. delete<T, R = AxiosResponse<ProcessedResponse<T>>>(
  35. url: string,
  36. config?: AxiosRequestConfig
  37. ): Promise<R>;
  38. }
  39. const instance: CustomAxiosInstance = axios.create({
  40. baseURL: "",
  41. timeout: 10000,
  42. headers: {
  43. "Content-Type": "application/json",
  44. },
  45. });
  46. const processResponse = <T>(
  47. response: AxiosResponse<ApiResponse<T>>
  48. ): ProcessedResponse<T> => {
  49. if (response.data.code === 200) {
  50. return {
  51. data: response.data.data,
  52. error: null,
  53. };
  54. } else {
  55. return {
  56. data: response.data.data || ({} as T),
  57. error: {
  58. msg: response.data.msg,
  59. msgZh: (response.data as unknown as ErrorResponse).msgZh,
  60. },
  61. };
  62. }
  63. };
  64. instance.interceptors.request.use(
  65. (config) => {
  66. return config;
  67. },
  68. (error) => {
  69. return Promise.reject(error);
  70. }
  71. );
  72. instance.interceptors.response.use(
  73. <T>(
  74. response: AxiosResponse<ApiResponse<T>>
  75. ): AxiosResponse<ProcessedResponse<T>> => {
  76. return { ...response, data: processResponse(response) };
  77. },
  78. (error) => {
  79. message.error(error?.response?.data?.msg || "Error");
  80. return Promise.reject(error);
  81. }
  82. );
  83. export default instance;