http.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import type { AxiosRequestConfig } from 'axios';
  2. import type { RequestOptions } from '@/types/axios';
  3. import { defHttp } from '@/core/utils/http/axios';
  4. import { useGlobSetting } from '@/core/hooks/setting';
  5. import { useMessage } from '@/core/hooks/web/useMessage';
  6. import { downloadByData } from '@/core/utils/file/download';
  7. export interface PageResult<T> {
  8. total: number;
  9. rows: T[];
  10. }
  11. export interface PageQuery {
  12. pageNum?: number;
  13. pageSize?: number;
  14. orderByColumn?: string;
  15. isAsc?: string;
  16. }
  17. /** AI 接口统一前缀:adminPath + /ai/...(urlPrefix=/js 由 defHttp 自动补) */
  18. export function aiUrl(path: string): string {
  19. const { adminPath } = useGlobSetting();
  20. const p = path.startsWith('/') ? path : `/${path}`;
  21. return `${adminPath}${p}`;
  22. }
  23. /** 把查询参数拼进 URL(PUT/DELETE 的 @RequestParam 场景) */
  24. export function withQuery(url: string, params?: Record<string, any>): string {
  25. if (!params) return url;
  26. const qs = Object.keys(params)
  27. .filter((key) => params[key] !== undefined && params[key] !== null)
  28. .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
  29. .join('&');
  30. if (!qs) return url;
  31. return `${url}${url.includes('?') ? '&' : '?'}${qs}`;
  32. }
  33. export function cleanParams(params?: Record<string, any>): Record<string, any> | undefined {
  34. if (!params) return undefined;
  35. const result: Record<string, any> = {};
  36. Object.keys(params).forEach((key) => {
  37. const value = params[key];
  38. if (value !== undefined && value !== null && value !== '') {
  39. result[key] = value;
  40. }
  41. });
  42. return result;
  43. }
  44. export function aiGet<T = any>(path: string, params?: Record<string, any>, options?: RequestOptions): Promise<T> {
  45. return defHttp.get<T>({ url: aiUrl(path), params: cleanParams(params) }, options);
  46. }
  47. /** 分页列表接口:后端 total 可能序列化为字符串,统一归一为 number 供 BasicTable 分页消费 */
  48. export async function aiPage<T = any>(path: string, params?: Record<string, any>): Promise<PageResult<T>> {
  49. const res = await aiGet<PageResult<T>>(path, params);
  50. return { total: Number(res?.total ?? 0), rows: res?.rows ?? [] };
  51. }
  52. export function aiPost<T = any>(path: string, data?: any): Promise<T> {
  53. return defHttp.postJson<T>({ url: aiUrl(path), data });
  54. }
  55. export function aiPut<T = any>(path: string, data?: any): Promise<T> {
  56. return defHttp.put<T>({
  57. url: aiUrl(path),
  58. data,
  59. headers: { 'Content-Type': 'application/json' },
  60. });
  61. }
  62. /** PUT + 查询参数(后端 @RequestParam,例如重命名/置顶/权限模式) */
  63. export function aiPutQuery<T = any>(path: string, params: Record<string, any>): Promise<T> {
  64. return defHttp.put<T>({ url: withQuery(aiUrl(path), params) });
  65. }
  66. export function aiDelete<T = any>(path: string, params?: Record<string, any>, options?: RequestOptions): Promise<T> {
  67. return defHttp.delete<T>({ url: aiUrl(path), params: cleanParams(params) }, options);
  68. }
  69. /** DELETE + JSON body(资源解绑等) */
  70. export function aiDeleteBody<T = any>(path: string, data?: any): Promise<T> {
  71. return defHttp.delete<T>({
  72. url: aiUrl(path),
  73. data,
  74. headers: { 'Content-Type': 'application/json' },
  75. });
  76. }
  77. /**
  78. * 上传到 /resource/oss/upload(返回 OssDTO,含 ossId/createBy)
  79. *
  80. * <p>{@code defHttp.uploadFile} 直接调用 axiosInstance.request,不经过全局
  81. * transformRequestHook,拿到的是原生 AxiosResponse(body 形如 {@code { code, msg, data }})。
  82. * 这里统一拆包并判定失败,避免调用方把响应对象当 OssDTO 用:ossId 为空会让后端
  83. * 文档登记报「请先上传文件」。</p>
  84. */
  85. export async function aiUpload(file: File, onUploadProgress?: (e: any) => void): Promise<any> {
  86. const { ctxPath, adminPath } = useGlobSetting();
  87. const res: any = await defHttp.uploadFile(
  88. {
  89. url: ctxPath + adminPath + '/resource/oss/upload',
  90. onUploadProgress,
  91. },
  92. { file, filename: file.name },
  93. );
  94. if (res?.status >= 400) {
  95. throw new Error(res?.data?.msg || res?.data?.message || `文件上传失败(HTTP ${res?.status})`);
  96. }
  97. // 若将来 uploadFile 接入统一转换,res 本身就是业务数据,此时无 code 字段,原样返回
  98. const body = res?.data && typeof res.data === 'object' ? res.data : res;
  99. if (!body) {
  100. throw new Error('文件上传失败');
  101. }
  102. if (body.code !== undefined && body.code !== 200) {
  103. throw new Error(body.msg || body.message || '文件上传失败');
  104. }
  105. return body.code !== undefined ? body.data : body;
  106. }
  107. /** 导出 xlsx(后端返回二进制流) */
  108. export async function aiDownload(
  109. path: string,
  110. params: Record<string, any> | undefined,
  111. filename: string,
  112. method: 'GET' | 'POST' = 'POST',
  113. ): Promise<void> {
  114. const { urlPrefix, adminPath } = useGlobSetting();
  115. const url = `${urlPrefix}${adminPath}${path.startsWith('/') ? path : `/${path}`}`;
  116. // 空筛选项不参与导出:避免 undefined/null/'' 被序列化成字符串 "null",
  117. // 导致后端把 agentId 等 Long 字段转换失败(HTTP 400)。
  118. const clean = cleanParams(params);
  119. const config: AxiosRequestConfig = {
  120. url: withQuery(url, method === 'GET' ? clean : undefined),
  121. method,
  122. data: method === 'POST' ? clean : undefined,
  123. responseType: 'blob',
  124. };
  125. try {
  126. const res: any = await defHttp.request(config, {
  127. isReturnNativeResponse: true,
  128. isTransformResponse: false,
  129. skipErrorMessage: true,
  130. joinPrefix: false,
  131. });
  132. const blob = res?.data instanceof Blob ? res.data : new Blob([res?.data]);
  133. downloadByData(blob as BlobPart, filename);
  134. } catch (error) {
  135. const message = await resolveDownloadError(error);
  136. useMessage().showMessage(`导出失败:${message}`, 'error');
  137. throw new Error(message);
  138. }
  139. }
  140. /**
  141. * 解析导出失败原因。
  142. *
  143. * <p>导出使用 blob 响应,HTTP 400 时错误体也是 Blob,不能按普通 JSON 读取;
  144. * 这里先按文本解析后取后端 message,避免只抛出无上下文的 Axios 错误。</p>
  145. */
  146. async function resolveDownloadError(error: any): Promise<string> {
  147. const data = error?.response?.data;
  148. if (data instanceof Blob) {
  149. try {
  150. const text = await data.text();
  151. try {
  152. const body = JSON.parse(text);
  153. return body?.message || body?.msg || '导出失败';
  154. } catch {
  155. const trimmed = text.trim();
  156. return trimmed ? trimmed.slice(0, 200) : '导出失败';
  157. }
  158. } catch {
  159. // 读取错误体失败时回退到通用提示
  160. }
  161. }
  162. return error?.response?.data?.message || error?.message || '导出失败';
  163. }