|
| 1 | +const API_BASE = '/api' |
| 2 | + |
| 3 | +interface ApiResponse<T> { |
| 4 | + code: number |
| 5 | + success?: boolean |
| 6 | + data: T |
| 7 | + message: string |
| 8 | +} |
| 9 | + |
| 10 | +export function getToken(): string | null { |
| 11 | + return localStorage.getItem('token') |
| 12 | +} |
| 13 | + |
| 14 | +export function logout() { |
| 15 | + localStorage.removeItem('token') |
| 16 | + localStorage.removeItem('token_expires') |
| 17 | + window.location.href = '/login' |
| 18 | +} |
| 19 | + |
| 20 | +export function isAuthenticated(): boolean { |
| 21 | + const token = getToken() |
| 22 | + if (!token) return false |
| 23 | + |
| 24 | + const expires = localStorage.getItem('token_expires') |
| 25 | + if (expires && new Date(expires) < new Date()) { |
| 26 | + logout() |
| 27 | + return false |
| 28 | + } |
| 29 | + return true |
| 30 | +} |
| 31 | + |
| 32 | +export async function fetchAPI<T>(path: string, options?: RequestInit): Promise<T> { |
| 33 | + const headers: Record<string, string> = {} |
| 34 | + |
| 35 | + const token = getToken() |
| 36 | + if (token) { |
| 37 | + headers['Authorization'] = `Bearer ${token}` |
| 38 | + } |
| 39 | + |
| 40 | + if (options?.body) { |
| 41 | + headers['Content-Type'] = 'application/json' |
| 42 | + } |
| 43 | + |
| 44 | + const res = await fetch(`${API_BASE}${path}`, { |
| 45 | + headers, |
| 46 | + ...options, |
| 47 | + }) |
| 48 | + |
| 49 | + if (res.status === 401) { |
| 50 | + logout() |
| 51 | + throw new Error('登录已过期') |
| 52 | + } |
| 53 | + |
| 54 | + const body: ApiResponse<T> = await res.json().catch(() => ({ |
| 55 | + code: res.status, |
| 56 | + data: null as T, |
| 57 | + message: `HTTP ${res.status}`, |
| 58 | + })) |
| 59 | + if (body.code !== 0 || body.success === false) { |
| 60 | + throw new Error(body.message || `HTTP ${res.status}`) |
| 61 | + } |
| 62 | + return body.data |
| 63 | +} |
| 64 | + |
| 65 | +export const apiClient = { |
| 66 | + request: fetchAPI, |
| 67 | +} |
0 commit comments