kun-galgame-vue/src/utils/request.ts

93 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-09-24 13:46:04 +00:00
// 操作 cookie 的函数
import { getToken } from '@/utils/cookie'
2023-06-10 09:24:56 +00:00
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'
2023-06-11 08:50:46 +00:00
export type FetchOptions = {
2023-06-10 09:24:56 +00:00
method: HttpMethod
headers?: Record<string, string>
body?: BodyInit
}
const fetchRequest = async <T>(
url: string,
2023-06-10 09:24:56 +00:00
options: FetchOptions
): Promise<T> => {
try {
2023-06-14 11:09:55 +00:00
const baseUrl = import.meta.env.VITE_API_BASE_URL
const fullUrl = `${baseUrl}${url}`
const response = await fetch(fullUrl, options)
2023-06-10 09:24:56 +00:00
if (!response.ok) {
throw new Error('Request Error!')
}
const data: T = await response.json()
return data
} catch (error) {
2023-08-22 15:59:18 +00:00
console.error('Fetch Error:', error)
2023-06-10 09:24:56 +00:00
throw new Error('Request Error!')
}
}
2023-06-10 09:24:56 +00:00
const fetchGet = async <T>(
url: string,
headers?: Record<string, string>
): Promise<T> => {
const options: FetchOptions = {
method: 'GET',
headers: headers,
}
return await fetchRequest<T>(url, options)
}
const fetchPost = async <T>(
url: string,
body?: Record<string, any>,
headers?: Record<string, string>
): Promise<T> => {
const options: FetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers,
},
body: JSON.stringify(body),
}
return await fetchRequest<T>(url, options)
}
const fetchPut = async <T>(
url: string,
body?: Record<string, any>,
headers?: Record<string, string>
): Promise<T> => {
const options: FetchOptions = {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
...headers,
},
body: JSON.stringify(body),
}
return await fetchRequest<T>(url, options)
}
const fetchDelete = async <T>(
url: string,
headers?: Record<string, string>
): Promise<T> => {
const options: FetchOptions = {
method: 'DELETE',
headers: headers,
}
return await fetchRequest<T>(url, options)
}
export { fetchGet, fetchPost, fetchPut, fetchDelete }