| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178 |
- import type { AxiosRequestConfig } from 'axios';
- import type { RequestOptions } from '@/types/axios';
- import { defHttp } from '@/core/utils/http/axios';
- import { useGlobSetting } from '@/core/hooks/setting';
- import { useMessage } from '@/core/hooks/web/useMessage';
- import { downloadByData } from '@/core/utils/file/download';
- export interface PageResult<T> {
- total: number;
- rows: T[];
- }
- export interface PageQuery {
- pageNum?: number;
- pageSize?: number;
- orderByColumn?: string;
- isAsc?: string;
- }
- /** AI 接口统一前缀:adminPath + /ai/...(urlPrefix=/js 由 defHttp 自动补) */
- export function aiUrl(path: string): string {
- const { adminPath } = useGlobSetting();
- const p = path.startsWith('/') ? path : `/${path}`;
- return `${adminPath}${p}`;
- }
- /** 把查询参数拼进 URL(PUT/DELETE 的 @RequestParam 场景) */
- export function withQuery(url: string, params?: Record<string, any>): string {
- if (!params) return url;
- const qs = Object.keys(params)
- .filter((key) => params[key] !== undefined && params[key] !== null)
- .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
- .join('&');
- if (!qs) return url;
- return `${url}${url.includes('?') ? '&' : '?'}${qs}`;
- }
- export function cleanParams(params?: Record<string, any>): Record<string, any> | undefined {
- if (!params) return undefined;
- const result: Record<string, any> = {};
- Object.keys(params).forEach((key) => {
- const value = params[key];
- if (value !== undefined && value !== null && value !== '') {
- result[key] = value;
- }
- });
- return result;
- }
- export function aiGet<T = any>(path: string, params?: Record<string, any>, options?: RequestOptions): Promise<T> {
- return defHttp.get<T>({ url: aiUrl(path), params: cleanParams(params) }, options);
- }
- /** 分页列表接口:后端 total 可能序列化为字符串,统一归一为 number 供 BasicTable 分页消费 */
- export async function aiPage<T = any>(path: string, params?: Record<string, any>): Promise<PageResult<T>> {
- const res = await aiGet<PageResult<T>>(path, params);
- return { total: Number(res?.total ?? 0), rows: res?.rows ?? [] };
- }
- export function aiPost<T = any>(path: string, data?: any): Promise<T> {
- return defHttp.postJson<T>({ url: aiUrl(path), data });
- }
- export function aiPut<T = any>(path: string, data?: any): Promise<T> {
- return defHttp.put<T>({
- url: aiUrl(path),
- data,
- headers: { 'Content-Type': 'application/json' },
- });
- }
- /** PUT + 查询参数(后端 @RequestParam,例如重命名/置顶/权限模式) */
- export function aiPutQuery<T = any>(path: string, params: Record<string, any>): Promise<T> {
- return defHttp.put<T>({ url: withQuery(aiUrl(path), params) });
- }
- export function aiDelete<T = any>(path: string, params?: Record<string, any>, options?: RequestOptions): Promise<T> {
- return defHttp.delete<T>({ url: aiUrl(path), params: cleanParams(params) }, options);
- }
- /** DELETE + JSON body(资源解绑等) */
- export function aiDeleteBody<T = any>(path: string, data?: any): Promise<T> {
- return defHttp.delete<T>({
- url: aiUrl(path),
- data,
- headers: { 'Content-Type': 'application/json' },
- });
- }
- /**
- * 上传到 /resource/oss/upload(返回 OssDTO,含 ossId/createBy)
- *
- * <p>{@code defHttp.uploadFile} 直接调用 axiosInstance.request,不经过全局
- * transformRequestHook,拿到的是原生 AxiosResponse(body 形如 {@code { code, msg, data }})。
- * 这里统一拆包并判定失败,避免调用方把响应对象当 OssDTO 用:ossId 为空会让后端
- * 文档登记报「请先上传文件」。</p>
- */
- export async function aiUpload(file: File, onUploadProgress?: (e: any) => void): Promise<any> {
- const { ctxPath, adminPath } = useGlobSetting();
- const res: any = await defHttp.uploadFile(
- {
- url: ctxPath + adminPath + '/resource/oss/upload',
- onUploadProgress,
- },
- { file, filename: file.name },
- );
- if (res?.status >= 400) {
- throw new Error(res?.data?.msg || res?.data?.message || `文件上传失败(HTTP ${res?.status})`);
- }
- // 若将来 uploadFile 接入统一转换,res 本身就是业务数据,此时无 code 字段,原样返回
- const body = res?.data && typeof res.data === 'object' ? res.data : res;
- if (!body) {
- throw new Error('文件上传失败');
- }
- if (body.code !== undefined && body.code !== 200) {
- throw new Error(body.msg || body.message || '文件上传失败');
- }
- return body.code !== undefined ? body.data : body;
- }
- /** 导出 xlsx(后端返回二进制流) */
- export async function aiDownload(
- path: string,
- params: Record<string, any> | undefined,
- filename: string,
- method: 'GET' | 'POST' = 'POST',
- ): Promise<void> {
- const { urlPrefix, adminPath } = useGlobSetting();
- const url = `${urlPrefix}${adminPath}${path.startsWith('/') ? path : `/${path}`}`;
- // 空筛选项不参与导出:避免 undefined/null/'' 被序列化成字符串 "null",
- // 导致后端把 agentId 等 Long 字段转换失败(HTTP 400)。
- const clean = cleanParams(params);
- const config: AxiosRequestConfig = {
- url: withQuery(url, method === 'GET' ? clean : undefined),
- method,
- data: method === 'POST' ? clean : undefined,
- responseType: 'blob',
- };
- try {
- const res: any = await defHttp.request(config, {
- isReturnNativeResponse: true,
- isTransformResponse: false,
- skipErrorMessage: true,
- joinPrefix: false,
- });
- const blob = res?.data instanceof Blob ? res.data : new Blob([res?.data]);
- downloadByData(blob as BlobPart, filename);
- } catch (error) {
- const message = await resolveDownloadError(error);
- useMessage().showMessage(`导出失败:${message}`, 'error');
- throw new Error(message);
- }
- }
- /**
- * 解析导出失败原因。
- *
- * <p>导出使用 blob 响应,HTTP 400 时错误体也是 Blob,不能按普通 JSON 读取;
- * 这里先按文本解析后取后端 message,避免只抛出无上下文的 Axios 错误。</p>
- */
- async function resolveDownloadError(error: any): Promise<string> {
- const data = error?.response?.data;
- if (data instanceof Blob) {
- try {
- const text = await data.text();
- try {
- const body = JSON.parse(text);
- return body?.message || body?.msg || '导出失败';
- } catch {
- const trimmed = text.trim();
- return trimmed ? trimmed.slice(0, 200) : '导出失败';
- }
- } catch {
- // 读取错误体失败时回退到通用提示
- }
- }
- return error?.response?.data?.message || error?.message || '导出失败';
- }
|