client.ts 4.01 KB
import axios, { type AxiosRequestConfig, type AxiosError } from 'axios';

export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
  trace_id?: string;
}

export interface PaginatedResponse<T> {
  list: T[];
  page: number;
  page_size: number;
  total: number;
}

export class ApiError extends Error {
  constructor(message: string, public code: number) {
    super(message);
    this.name = 'ApiError';
  }
}

export function isApiError(error: unknown): error is ApiError {
  return error instanceof ApiError;
}

function getErrorMessageFromAxiosError(error: { response?: { status: number; data?: { message?: string } }; code?: string; message?: string }): string {
  if (error.code === 'ERR_NETWORK' || error.message === 'Network Error') {
    return '网络错误,请检查网络连接';
  }
  if (error.code === 'ECONNABORTED' || (error.message?.includes('timeout') ?? false)) {
    return '请求超时,请稍后重试';
  }
  if (error.response) {
    const responseData = error.response.data;
    if (responseData?.message) {
      return responseData.message;
    }
    return `HTTP 错误: ${error.response.status}`;
  }
  return error.message || '请求失败';
}

interface ApiClientConfig {
  baseURL?: string;
}

export function createApiClient(config?: ApiClientConfig) {
  const baseURL = config?.baseURL ?? import.meta.env.VITE_API_BASE_URL ?? '/api/v1';

  // 不在 axios.create 设置默认 Content-Type,让 axios 自动检测:
  // - FormData 自动设置为 multipart/form-data; boundary=...
  // - 其他数据需要在请求时显式设置 Content-Type
  const axiosInstance = axios.create({
    baseURL,
    timeout: 30000,
  });

  async function request<T>(requestConfig: AxiosRequestConfig): Promise<T> {
    try {
      const response = await axiosInstance.request<ApiResponse<T>>(requestConfig);
      const apiResponse = response.data;

      if (apiResponse.code === 200 || apiResponse.code === 201) {
        return apiResponse.data;
      }

      throw new ApiError(apiResponse.message || '请求失败', apiResponse.code);
    } catch (error) {
      if (isApiError(error)) {
        throw error;
      }

      // Check if error looks like an AxiosError (has response property)
      const axiosLikeError = error as { response?: { status: number; data?: { message?: string } }; code?: string; message?: string };
      if (axiosLikeError.response || axiosLikeError.code === 'ERR_NETWORK' || axiosLikeError.code === 'ECONNABORTED') {
        const message = getErrorMessageFromAxiosError(axiosLikeError);
        throw new ApiError(message, axiosLikeError.response?.status ?? 0);
      }

      throw new ApiError((error as Error).message || '请求失败', 0);
    }
  }

  function get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return request<T>({ ...config, method: 'GET', url });
  }

  function post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {
    // FormData: 不设置 Content-Type,让 axios 自动生成 multipart/form-data; boundary=...
    // 其他数据: 显式设置 Content-Type: application/json
    const headers = data instanceof FormData
      ? { ...config?.headers }
      : { ...config?.headers, 'Content-Type': 'application/json' };
    return request<T>({ ...config, method: 'POST', url, data, headers });
  }

  function put<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {
    // FormData: 不设置 Content-Type,让 axios 自动生成 multipart/form-data; boundary=...
    // 其他数据: 显式设置 Content-Type: application/json
    const headers = data instanceof FormData
      ? { ...config?.headers }
      : { ...config?.headers, 'Content-Type': 'application/json' };
    return request<T>({ ...config, method: 'PUT', url, data, headers });
  }

  function del<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return request<T>({ ...config, method: 'DELETE', url });
  }

  return {
    request,
    get,
    post,
    put,
    delete: del,
    axiosInstance,
  };
}

export const apiClient = createApiClient();