import { storage } from '../storage'; const BASE_URL = 'https://api.mixvideo.bowong.cc'; export interface ApiRequestOptions { method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; body?: string; params?: Record; headers?: Record; requiresAuth?: boolean; } async function getAuthToken(): Promise { return (await storage.getItem(`bestaibest.better-auth.session_token`)) || ''; } export async function apiRequest( endpoint: string, options: ApiRequestOptions = {} ): Promise { const { method = 'GET', body, params, headers = {}, requiresAuth = true, } = options; // 构建 URL const url = new URL(endpoint, BASE_URL); // 添加查询参数 if (params) { Object.entries(params).forEach(([key, value]) => { if (value !== undefined && value !== null) { url.searchParams.append(key, String(value)); } }); } // 准备请求头 const requestHeaders: Record = { 'Content-Type': 'application/json', ...headers, }; // 如果需要认证,添加 Bearer token if (requiresAuth) { const token = await getAuthToken(); if (token) { requestHeaders['Authorization'] = `Bearer ${token}`; } } // 发起请求 const response = await fetch(url.toString(), { method, headers: requestHeaders, body: method !== 'GET' ? body : undefined, }); // 检查响应状态 if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status}: ${errorText}`); } return response.json(); } export async function apiClient( endpoint: string, options: ApiRequestOptions = {} ): Promise { return apiRequest(endpoint, { ...options, requiresAuth: true, }); }