indexAi.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
  2. import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";
  3. import { LOGIN_URL } from "@/config";
  4. import { ElMessage } from "element-plus";
  5. import { ResultData } from "@/api/interface";
  6. import { ResultEnum } from "@/enums/httpEnum";
  7. import { checkStatus } from "./helper/checkStatus";
  8. import { AxiosCanceler } from "./helper/axiosCancel";
  9. import { useUserStore } from "@/stores/modules/user";
  10. import router from "@/routers";
  11. import { localGet, localSet } from "@/utils";
  12. import { cryptoUtil } from "@/utils/crypto";
  13. import { cryptoStrategy } from "@/utils/cryptoStrategy";
  14. export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  15. loading?: boolean;
  16. cancel?: boolean;
  17. encrypt?: boolean; // 是否加密请求参数
  18. }
  19. const config = {
  20. // AI服务地址,使用 /ai-api 前缀,由 VITE_PROXY_AI 代理到 http://192.168.2.250:9000
  21. baseURL: "/ai-api",
  22. // 设置超时时间
  23. timeout: ResultEnum.TIMEOUT as number,
  24. // 跨域时候允许携带凭证
  25. withCredentials: true
  26. };
  27. const axiosCanceler = new AxiosCanceler();
  28. // AI Token存储key
  29. const AI_TOKEN_KEY = "ai-service-token";
  30. /**
  31. * 获取AI服务Token
  32. */
  33. const getAiToken = (): string | null => {
  34. return localGet(AI_TOKEN_KEY) || null;
  35. };
  36. /**
  37. * 设置AI服务Token
  38. */
  39. const setAiToken = (token: string) => {
  40. localSet(AI_TOKEN_KEY, token);
  41. };
  42. /**
  43. * AI服务登录
  44. * @returns AI服务token,如果登录失败返回null
  45. */
  46. export const aiLogin = async (): Promise<string | null> => {
  47. try {
  48. // 获取主系统的用户信息
  49. const userInfo = localGet("geeker-user");
  50. if (!userInfo || !userInfo.userInfo) {
  51. console.error("无法获取用户信息,AI服务登录失败");
  52. return null;
  53. }
  54. // 创建一个临时的axios实例用于登录(不使用拦截器,避免循环)
  55. const loginInstance = axios.create({
  56. baseURL: "/ai-api",
  57. timeout: ResultEnum.TIMEOUT as number,
  58. withCredentials: true
  59. });
  60. // 调用AI登录接口,使用主系统的用户名和密码
  61. // 根据实际接口要求调整参数
  62. const loginParams: any = {
  63. username: userInfo.userInfo.nickName,
  64. password: userInfo.userInfo.password
  65. };
  66. // 如果没有密码,可能需要使用主系统的token来换取AI服务的token
  67. // 或者使用其他认证方式,这里需要根据实际接口文档调整
  68. if (!loginParams.password) {
  69. // 如果主系统没有存储密码,可能需要使用token或其他方式
  70. // 暂时尝试使用主系统的token
  71. loginParams.token = userInfo.token;
  72. }
  73. const response = await loginInstance.post("/ai/user-auth-core/api/v1/auth/login", loginParams);
  74. // 根据实际返回格式调整
  75. if (response.data) {
  76. // 可能返回格式:{ code: 200, data: { token: "..." } }
  77. // 或者:{ code: 200, token: "..." }
  78. const token = response.data.data?.token || response.data.token;
  79. if (token) {
  80. setAiToken(token);
  81. return token;
  82. }
  83. }
  84. return null;
  85. } catch (error: any) {
  86. console.error("AI服务登录失败:", error);
  87. // 如果登录失败,返回null,让请求失败
  88. return null;
  89. }
  90. };
  91. class RequestHttp {
  92. service: AxiosInstance;
  93. private isLoggingIn = false; // 防止重复登录
  94. private loginPromise: Promise<string | null> | null = null; // 登录Promise,用于并发请求时共享登录结果
  95. public constructor(config: AxiosRequestConfig) {
  96. // instantiation
  97. this.service = axios.create(config);
  98. /**
  99. * @description 请求拦截器
  100. * 客户端发送请求 -> [请求拦截器] -> 服务器
  101. * token校验(JWT) : 先获取AI服务token,如果没有则先登录获取token
  102. */
  103. this.service.interceptors.request.use(
  104. async (config: CustomAxiosRequestConfig) => {
  105. // 重复请求不需要取消,在 api 服务中通过指定的第三个参数: { cancel: false } 来控制
  106. config.cancel ??= true;
  107. config.cancel && axiosCanceler.addPending(config);
  108. // 当前请求不需要显示 loading,在 api 服务中通过指定的第三个参数: { loading: false } 来控制
  109. config.loading ??= true;
  110. config.loading && showFullScreenLoading();
  111. // 获取AI服务token
  112. let aiToken = getAiToken();
  113. // 如果没有token,先登录获取token
  114. if (!aiToken) {
  115. // 如果正在登录,等待登录完成
  116. if (this.isLoggingIn && this.loginPromise) {
  117. aiToken = await this.loginPromise;
  118. } else {
  119. // 开始登录
  120. this.isLoggingIn = true;
  121. this.loginPromise = aiLogin();
  122. aiToken = await this.loginPromise;
  123. this.isLoggingIn = false;
  124. this.loginPromise = null;
  125. }
  126. }
  127. // 设置Authorization header
  128. if (config.headers) {
  129. if (typeof config.headers.set === "function") {
  130. config.headers.set("Authorization", aiToken || "");
  131. } else {
  132. (config.headers as any)["Authorization"] = aiToken || "";
  133. }
  134. }
  135. // 加密处理
  136. if (cryptoStrategy.shouldEncrypt(config) && config.data) {
  137. try {
  138. config.data = cryptoUtil.encrypt(config.data);
  139. } catch (error) {
  140. return Promise.reject(error);
  141. }
  142. }
  143. return config;
  144. },
  145. (error: AxiosError) => {
  146. return Promise.reject(error);
  147. }
  148. );
  149. /**
  150. * @description 响应拦截器
  151. * 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
  152. */
  153. this.service.interceptors.response.use(
  154. (response: AxiosResponse & { config: CustomAxiosRequestConfig }) => {
  155. const { data, config, headers } = response;
  156. const userStore = useUserStore();
  157. axiosCanceler.removePending(config);
  158. config.loading && tryHideFullScreenLoading();
  159. // 解密处理
  160. if (cryptoStrategy.shouldDecrypt(config, headers, data)) {
  161. try {
  162. const decryptedData = cryptoUtil.decrypt(data);
  163. response.data = decryptedData;
  164. } catch (error) {
  165. console.error("解密失败:", error);
  166. ElMessage.error("响应数据解密失败");
  167. return Promise.reject(new Error("响应数据解密失败"));
  168. }
  169. }
  170. const processedData = response.data;
  171. // 登录失效 - AI服务token过期,清除token,下次请求时会重新登录
  172. if (processedData.code == ResultEnum.OVERDUE || processedData.code === 401) {
  173. localSet(AI_TOKEN_KEY, null);
  174. // 如果是登录接口本身失败,不显示错误(避免循环)
  175. if (!config.url?.includes("/auth/login")) {
  176. ElMessage.error(processedData.msg || "AI服务认证失败,请重试");
  177. }
  178. return Promise.reject(processedData);
  179. }
  180. // 全局错误信息拦截(防止下载文件的时候返回数据流,没有 code 直接报错)
  181. if (processedData.code && processedData.code !== ResultEnum.SUCCESS) {
  182. ElMessage.error(processedData.msg);
  183. return Promise.reject(processedData);
  184. }
  185. // 成功请求(在页面上除非特殊情况,否则不用处理失败逻辑)
  186. return processedData;
  187. },
  188. async (error: AxiosError) => {
  189. const { response } = error;
  190. tryHideFullScreenLoading();
  191. // 请求超时 && 网络错误单独判断,没有 response
  192. if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时!请您稍后重试");
  193. if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误!请您稍后重试");
  194. // 根据服务器响应的错误状态码,做不同的处理
  195. if (response && response.data && (response.data as any).message) {
  196. ElMessage.error((response.data as any).message);
  197. } else {
  198. if (response) checkStatus(response.status);
  199. }
  200. // 服务器结果都没有返回(可能服务器错误可能客户端断网),断网处理:可以跳转到断网页面
  201. if (!window.navigator.onLine) router.replace("/500");
  202. return Promise.reject(error);
  203. }
  204. );
  205. }
  206. /**
  207. * @description 常用请求方法封装
  208. */
  209. get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  210. return this.service.get(url, { params, ..._object });
  211. }
  212. post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
  213. return this.service.post(url, params, _object);
  214. }
  215. put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  216. return this.service.put(url, params, _object);
  217. }
  218. delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
  219. return this.service.delete(url, { params, ..._object });
  220. }
  221. download(url: string, params?: object, _object = {}): Promise<BlobPart> {
  222. return this.service.post(url, params, { ..._object, responseType: "blob" });
  223. }
  224. }
  225. export default new RequestHttp(config);