// 使用用户 store import { useKUNGalgameUserStore } from '@/store/modules/kungalgamer' // 错误处理函数 import { onRequestError } from '@/error/onRequestError' type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' export type FetchOptions = { method: HttpMethod credentials: 'include' headers?: Record body?: BodyInit } // fetch 请求函数 const kunFetchRequest = async ( url: string, options: FetchOptions ): Promise => { const baseUrl = import.meta.env.VITE_API_BASE_URL const fullUrl = `${baseUrl}${url}` // 在请求头中添加 token const headers = { ...options.headers, Authorization: `Bearer ${useKUNGalgameUserStore().getToken()}`, } const response = await fetch(fullUrl, { ...options, headers }) // 后端的一切正常响应都被设为 200 了 if (response.status != 200) { // 处理错误,token 过期 await onRequestError(response) throw new Error('KUNGalgame Fetch Error occurred, but no problem') } const data: T = await response.json() return data } const fetchGet = async ( url: string, headers?: Record ): Promise => { const options: FetchOptions = { method: 'GET', credentials: 'include', headers: headers, } return await kunFetchRequest(url, options) } const fetchPost = async ( url: string, body?: Record, headers?: Record ): Promise => { const options: FetchOptions = { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', ...headers, }, body: JSON.stringify(body), } return await kunFetchRequest(url, options) } const fetchPut = async ( url: string, body?: Record, headers?: Record ): Promise => { const options: FetchOptions = { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json', ...headers, }, body: JSON.stringify(body), } return await kunFetchRequest(url, options) } const fetchDelete = async ( url: string, headers?: Record ): Promise => { const options: FetchOptions = { method: 'DELETE', credentials: 'include', headers: headers, } return await kunFetchRequest(url, options) } export { fetchGet, fetchPost, fetchPut, fetchDelete }