axios.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import { Response } from "@/types";
  2. import { Toast } from "antd-mobile";
  3. import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from "axios";
  4. import type { AxiosOptions } from "./type";
  5. import { setupConfig } from "@/api/setup";
  6. import { defaultLocale } from "@/i18n/routing";
  7. import { getCookies, getToken } from "@/utils/Cookies";
  8. interface CustomRequestConfig {
  9. toast?: boolean;
  10. }
  11. const getInitBaseUrl = () => {
  12. const str = sessionStorage.getItem("config");
  13. if (str) return JSON.parse(str);
  14. return fetch("https://static.tiktokjakjkl.icu/test/index.json")
  15. .then((res) => res.json())
  16. .then((config) => {
  17. sessionStorage.setItem("config", JSON.stringify(config));
  18. return config;
  19. });
  20. };
  21. const errorHandle = (status: number): void => {
  22. const msgMap: Record<number, string> = {
  23. 1022: "Restrição anormal de conta",
  24. 6002: "Nenhum bônus não pode ser reclamado no modo bônus ativado",
  25. 6001: "As condições do bônus de esvaziamento não são atendidas",
  26. };
  27. const msg = msgMap[status];
  28. if (msg) {
  29. Toast.show({
  30. icon: "fail",
  31. content: msg,
  32. });
  33. }
  34. };
  35. export default class Request {
  36. private axiosInstance: AxiosInstance;
  37. private readonly options: AxiosOptions;
  38. constructor(options: AxiosOptions) {
  39. this.axiosInstance = axios.create(options);
  40. this.options = options;
  41. this.setupInterceptors();
  42. }
  43. setupInterceptors() {
  44. // 定义拦截器
  45. const {
  46. options: { transform },
  47. axiosInstance,
  48. } = this;
  49. // 如果没有自定义拦截器则返回
  50. if (!transform) {
  51. return;
  52. }
  53. // 解包拦截器
  54. const {
  55. requestInterceptor,
  56. requestInterceptorCatch,
  57. responseInterceptor,
  58. responseInterceptorCatch,
  59. } = transform;
  60. /**
  61. * @description 全局请求拦截
  62. */
  63. axiosInstance.interceptors.request.use(
  64. async (config: InternalAxiosRequestConfig & CustomRequestConfig) => {
  65. const result = await setupConfig();
  66. config.baseURL = result.NEXT_PUBLIC_BASE_URL;
  67. if (requestInterceptor) {
  68. config = requestInterceptor(config);
  69. // header请求头添加token
  70. config.headers["Token"] = getToken() || "";
  71. config.headers["language"] = getCookies("language") || defaultLocale;
  72. if (config && config?.toast) {
  73. Toast.show({
  74. icon: "loading",
  75. maskClickable: false,
  76. });
  77. }
  78. }
  79. return config;
  80. },
  81. (error) => {
  82. if (requestInterceptorCatch) {
  83. requestInterceptorCatch(error);
  84. }
  85. }
  86. );
  87. /**
  88. * @description 全局响应拦截
  89. */
  90. axiosInstance.interceptors.response.use(
  91. (res) => {
  92. // Toast.clear();
  93. if (responseInterceptor) {
  94. res = responseInterceptor(res);
  95. }
  96. return res;
  97. },
  98. (error) => {
  99. if (responseInterceptorCatch) {
  100. responseInterceptorCatch(error);
  101. }
  102. Toast.clear();
  103. }
  104. );
  105. }
  106. /**
  107. * @description 单个实列请求
  108. */
  109. request<T = unknown, R = unknown>(config: AxiosOptions): Promise<Response<T> & R> {
  110. return new Promise((resolve, reject) => {
  111. this.axiosInstance
  112. .request<unknown, AxiosResponse<Response<T> & R>>(config)
  113. .then(async (res) => {
  114. const { transform } = config;
  115. if (transform && transform.responseInterceptor) {
  116. res = transform.responseInterceptor(res);
  117. }
  118. if (res && res.data && res.data.code === 200) {
  119. resolve(res.data);
  120. } else {
  121. errorHandle(res.data.code);
  122. reject(res);
  123. }
  124. })
  125. .catch((error) => {
  126. reject(error);
  127. });
  128. });
  129. }
  130. get<T, R = unknown>(config: AxiosOptions): Promise<Response<T> & R> {
  131. return this.request({ ...config, method: "get" });
  132. }
  133. post<T, R = unknown>(config: AxiosOptions): Promise<Response<T> & R> {
  134. return this.request({ ...config, method: "post" });
  135. }
  136. put<T, R = unknown>(config: AxiosOptions): Promise<Response<T> & R> {
  137. return this.request({ ...config, method: "put" });
  138. }
  139. delete<T, R = unknown>(config: AxiosOptions): Promise<Response<T> & R> {
  140. return this.request({ ...config, method: "delete" });
  141. }
  142. }