|
| 1 | +import { API_URL } from '../config'; |
| 2 | + |
| 3 | +let accessToken: string | null = null; |
| 4 | + |
| 5 | +export function getAccessToken(): string | null { |
| 6 | + return accessToken; |
| 7 | +} |
| 8 | + |
| 9 | +export function setAccessToken(token: string | null) { |
| 10 | + accessToken = token; |
| 11 | +} |
| 12 | + |
| 13 | +export class AuthError extends Error { |
| 14 | + constructor(message: string) { |
| 15 | + super(message); |
| 16 | + this.name = 'AuthError'; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +export class ApiError extends Error { |
| 21 | + status: number; |
| 22 | + data: unknown; |
| 23 | + |
| 24 | + constructor(status: number, data: unknown) { |
| 25 | + super( |
| 26 | + typeof data === 'object' && data !== null && 'message' in data |
| 27 | + ? String((data as { message: string }).message) |
| 28 | + : `Request failed with status ${status}`, |
| 29 | + ); |
| 30 | + this.name = 'ApiError'; |
| 31 | + this.status = status; |
| 32 | + this.data = data; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +async function refreshToken(): Promise<boolean> { |
| 37 | + try { |
| 38 | + const res = await fetch(`${API_URL}/auth/refresh`, { |
| 39 | + method: 'POST', |
| 40 | + credentials: 'include', |
| 41 | + headers: { 'Content-Type': 'application/json' }, |
| 42 | + }); |
| 43 | + if (!res.ok) return false; |
| 44 | + const data = await res.json(); |
| 45 | + setAccessToken(data.accessToken); |
| 46 | + return true; |
| 47 | + } catch { |
| 48 | + return false; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +export async function apiClient<T>(path: string, options?: RequestInit): Promise<T> { |
| 53 | + const headers: Record<string, string> = { |
| 54 | + 'Content-Type': 'application/json', |
| 55 | + ...((options?.headers as Record<string, string>) || {}), |
| 56 | + }; |
| 57 | + |
| 58 | + const token = getAccessToken(); |
| 59 | + if (token) { |
| 60 | + headers['Authorization'] = `Bearer ${token}`; |
| 61 | + } |
| 62 | + |
| 63 | + const res = await fetch(`${API_URL}${path}`, { |
| 64 | + ...options, |
| 65 | + credentials: 'include', |
| 66 | + headers, |
| 67 | + }); |
| 68 | + |
| 69 | + if (res.status === 401) { |
| 70 | + const refreshed = await refreshToken(); |
| 71 | + if (refreshed) return apiClient(path, options); |
| 72 | + throw new AuthError('Session expired'); |
| 73 | + } |
| 74 | + |
| 75 | + if (!res.ok) { |
| 76 | + const data = await res.json().catch(() => ({})); |
| 77 | + throw new ApiError(res.status, data); |
| 78 | + } |
| 79 | + |
| 80 | + const text = await res.text(); |
| 81 | + if (!text) return undefined as T; |
| 82 | + return JSON.parse(text) as T; |
| 83 | +} |
0 commit comments