123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import axios from "axios";
  2. import React from "react";
  3. import { message } from "antd";
  4. import { getToken, setToken } from "./token";
  5. const instance = axios.create({
  6. baseURL: import.meta.env.VITE_SERVER_BASE,
  7. timeout: 10000,
  8. // withCredentials: true, // 跨域
  9. });
  10. // 添加请求拦截器
  11. instance.interceptors.request.use(
  12. function (config) {
  13. const {
  14. headers = {},
  15. method = "get",
  16. responseType = "json",
  17. download = false,
  18. silent,
  19. params = {},
  20. } = config;
  21. const token = getToken();
  22. let noTip = silent;
  23. if (noTip === undefined) {
  24. noTip = method.toLocaleLowerCase() === "get" ? true : false;
  25. }
  26. // 在发送请求之前做些什么
  27. return {
  28. ...config,
  29. params,
  30. silent: noTip,
  31. headers: {
  32. "Content-Type": "application/json;charset=utf-8",
  33. ...headers,
  34. Authorization: token,
  35. "x-client-type": "pc.admin",
  36. },
  37. responseType: download ? "blob" : responseType,
  38. };
  39. },
  40. function (error) {
  41. // 对请求错误做些什么
  42. return Promise.reject(error);
  43. }
  44. );
  45. // 添加响应拦截器
  46. instance.interceptors.response.use(
  47. function (response) {
  48. // 1000 范围内的状态码都会触发该函数。
  49. // 对响应数据做点什么
  50. const { data, config } = response;
  51. console.log(response)
  52. if (config.download && !data.code) {
  53. return downloadBlob(response, "下载文件");
  54. }
  55. if (data.code === 200) {
  56. if (data.data?.token) {
  57. setToken(data.data.token);
  58. }
  59. if (!config.silent) {
  60. message.success("操作成功");
  61. }
  62. return data.data;
  63. } else if (data.code === 401) {
  64. if (!config.silent) {
  65. message.error("未登录或者超时, 请重新登录");
  66. }
  67. } else {
  68. console.log(config);
  69. if (!config.silent) {
  70. const errMsg = data.msg || "系统错误";
  71. message.error(errMsg.indexOf("exception") > -1 ? "服务异常" : errMsg);
  72. }
  73. }
  74. return Promise.reject(response);
  75. },
  76. function (error) {
  77. // 超出 1000 范围的状态码都会触发该函数。
  78. // 对响应错误做点什么
  79. console.error(error);
  80. return Promise.reject("网络异常, 请重试...");
  81. }
  82. );
  83. export default instance;
  84. export function queryTable(apiRequest) {
  85. return function (params) {
  86. const { pageSize } = params;
  87. return apiRequest({
  88. ...params,
  89. pageSize,
  90. pageNum: params.current,
  91. })
  92. .then((res) => {
  93. return {
  94. data: res.records,
  95. success: true,
  96. total: res.total,
  97. };
  98. })
  99. .catch((err) => {
  100. return {
  101. success: false,
  102. };
  103. });
  104. };
  105. }
  106. function getValueOfType(value, type) {
  107. if (type == "string") return `${value}`;
  108. if (type == "int" || type == "integer") return value - 0;
  109. return value;
  110. }
  111. export function queryDict(
  112. apiRequest,
  113. { labelKey = "name", valueKey = "id", valueType }
  114. ) {
  115. return function (params) {
  116. const { current, pageSize, ...leftParams } = params || {};
  117. return apiRequest({
  118. pageSize: 9999,
  119. pageNum: 1,
  120. ...(leftParams || {}),
  121. })
  122. .then((res) => {
  123. return res?.records?.map((x) => ({
  124. label: x[labelKey],
  125. value: getValueOfType(x[valueKey], valueType),
  126. ...x,
  127. }));
  128. })
  129. .catch((err) => {
  130. return {
  131. success: false,
  132. };
  133. });
  134. };
  135. }
  136. export function restful(url) {
  137. const list = (params) => instance.get(url, { params });
  138. const get = (id) => instance.get(`${url}/${id}`);
  139. const add = (data) => instance.post(url, data);
  140. const update = (id, data) => instance.put(`${url}/${id}`, data);
  141. const del = (id) => instance.delete(`${url}/${id}`);
  142. return [list, get, add, update, del];
  143. }
  144. export function useRequest(fn) {
  145. const [loading, setLoading] = React.useState(false);
  146. const p = (...args) =>
  147. new Promise((resolve, reject) => {
  148. setLoading(true);
  149. fn(...args)
  150. .then((res) => {
  151. setLoading(false);
  152. resolve(res);
  153. })
  154. .catch((e) => {
  155. setLoading(false);
  156. reject(e);
  157. });
  158. });
  159. return [loading, p];
  160. }
  161. function downloadBlob(response) {
  162. let fileName = "未知文件";
  163. const contentType = response.headers["content-type"];
  164. const contentDisposition = response.headers["content-disposition"];
  165. if (contentDisposition) {
  166. const parts = contentDisposition.split(";filename=");
  167. if (parts[1]) {
  168. fileName = decodeURIComponent(parts[1]);
  169. }
  170. }
  171. const url = window.URL.createObjectURL(
  172. new Blob([response.data], { type: contentType })
  173. );
  174. const link = document.createElement("a");
  175. link.href = url;
  176. link.setAttribute("download", fileName);
  177. link.click();
  178. window.URL.revokeObjectURL(url);
  179. }