/** * API 客户端配置 * 可以根据项目需求使用 axios、fetch 或其他 HTTP 客户端 */ const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "/api"; export interface ApiResponse { data: T; message?: string; code?: number; } export interface ApiError { message: string; code?: number; } /** * 基础请求函数 */ export async function request( endpoint: string, options?: RequestInit, ): Promise> { const url = `${API_BASE_URL}${endpoint}`; try { const response = await fetch(url, { ...options, headers: { "Content-Type": "application/json", ...options?.headers, }, }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = (await response.json()) as ApiResponse; return data; } catch (error) { throw { message: error instanceof Error ? error.message : "Unknown error", code: 500, } as ApiError; } } /** * GET 请求 */ export function get(endpoint: string, options?: RequestInit) { return request(endpoint, { ...options, method: "GET" }); } /** * POST 请求 */ export function post( endpoint: string, data?: unknown, options?: RequestInit, ) { return request(endpoint, { ...options, method: "POST", body: data ? JSON.stringify(data) : undefined, }); } /** * PUT 请求 */ export function put( endpoint: string, data?: unknown, options?: RequestInit, ) { return request(endpoint, { ...options, method: "PUT", body: data ? JSON.stringify(data) : undefined, }); } /** * DELETE 请求 */ export function del(endpoint: string, options?: RequestInit) { return request(endpoint, { ...options, method: "DELETE" }); }