// 操作 cookie 的函数 import { getToken } from '@/utils/cookie' type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' export type FetchOptions = { method: HttpMethod headers?: Record body?: BodyInit } const fetchRequest = async ( url: string, options: FetchOptions ): Promise => { try { const baseUrl = import.meta.env.VITE_API_BASE_URL const fullUrl = `${baseUrl}${url}` const response = await fetch(fullUrl, options) if (!response.ok) { throw new Error('Request Error!') } const data: T = await response.json() return data } catch (error) { console.error('Fetch Error:', error) throw new Error('Request Error!') } } const fetchGet = async ( url: string, headers?: Record ): Promise => { const options: FetchOptions = { method: 'GET', headers: headers, } return await fetchRequest(url, options) } const fetchPost = async ( url: string, body?: Record, headers?: Record ): Promise => { const options: FetchOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers, }, body: JSON.stringify(body), } return await fetchRequest(url, options) } const fetchPut = async ( url: string, body?: Record, headers?: Record ): Promise => { const options: FetchOptions = { method: 'PUT', headers: { 'Content-Type': 'application/json', ...headers, }, body: JSON.stringify(body), } return await fetchRequest(url, options) } const fetchDelete = async ( url: string, headers?: Record ): Promise => { const options: FetchOptions = { method: 'DELETE', headers: headers, } return await fetchRequest(url, options) } export { fetchGet, fetchPost, fetchPut, fetchDelete }