Files
dreamweaver/admin-frontend/src/api/client.ts

58 lines
1.4 KiB
TypeScript

const BASE_URL = ''
class ApiClient {
async request<T>(url: string, options: RequestInit = {}): Promise<T> {
const headers = new Headers(options.headers || {})
const isFormData = options.body instanceof FormData
if (!isFormData && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json')
}
const response = await fetch(`${BASE_URL}${url}`, {
...options,
credentials: 'include',
headers,
})
if (!response.ok) {
const error = await response.json().catch(() => ({ detail: '请求失败' }))
throw new Error(error.detail || '请求失败')
}
if (response.status === 204 || response.status === 205) {
return undefined as T
}
const contentType = response.headers.get('content-type') || ''
if (!contentType.includes('application/json')) {
return undefined as T
}
return response.json()
}
get<T>(url: string): Promise<T> {
return this.request<T>(url)
}
post<T>(url: string, data?: unknown): Promise<T> {
return this.request<T>(url, {
method: 'POST',
body: data ? JSON.stringify(data) : undefined,
})
}
put<T>(url: string, data?: unknown): Promise<T> {
return this.request<T>(url, {
method: 'PUT',
body: data ? JSON.stringify(data) : undefined,
})
}
delete<T>(url: string): Promise<T> {
return this.request<T>(url, { method: 'DELETE' })
}
}
export const api = new ApiClient()