Spaces:
Sleeping
Sleeping
| import axios, { AxiosError } from 'axios' | |
| const API_BASE = '/api' | |
| // ββ Request / Response types ββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| export interface LoginRequest { | |
| email: string | |
| password: string | |
| } | |
| export interface LoginResponse { | |
| access_token: string | |
| token_type: 'bearer' | |
| user: { | |
| id: string | |
| email: string | |
| full_name: string | |
| role: 'doctor' | 'admin' | |
| } | |
| } | |
| export interface RegisterRequest { | |
| full_name: string | |
| email: string | |
| password: string | |
| confirm_password: string | |
| } | |
| export interface RegisterResponse { | |
| message: string // "ΔΔng kΓ½ thΓ nh cΓ΄ng. Vui lΓ²ng kiα»m tra email Δα» xΓ‘c thα»±c tΓ i khoαΊ£n." | |
| } | |
| export interface ForgotPasswordRequest { | |
| email: string | |
| } | |
| // ββ Error normalizer ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| function normalizeError(err: unknown): never { | |
| if (err instanceof AxiosError) { | |
| if (!err.response) { | |
| throw new Error( | |
| 'KhΓ΄ng thα» kαΊΏt nα»i ΔαΊΏn mΓ‘y chα»§ (cα»ng 8000). ' + | |
| 'Vui lΓ²ng khα»i Δα»ng Python Backend Server rα»i thα» lαΊ‘i.', | |
| ) | |
| } | |
| const body = err.response.data as Record<string, unknown> | undefined | |
| const detail = | |
| (body?.detail as string | undefined) ?? | |
| (body?.message as string | undefined) ?? | |
| (body?.error as string | undefined) ?? | |
| err.message | |
| throw new Error(detail) | |
| } | |
| throw err | |
| } | |
| // ββ API functions βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| export async function login(payload: LoginRequest): Promise<LoginResponse> { | |
| try { | |
| const { data } = await axios.post<LoginResponse>(`${API_BASE}/auth/login`, payload) | |
| return data | |
| } catch (err) { | |
| normalizeError(err) | |
| } | |
| } | |
| export async function register(payload: RegisterRequest): Promise<RegisterResponse> { | |
| try { | |
| const { data } = await axios.post<RegisterResponse>(`${API_BASE}/auth/register`, payload) | |
| return data | |
| } catch (err) { | |
| normalizeError(err) | |
| } | |
| } | |
| export async function forgotPassword(payload: ForgotPasswordRequest): Promise<{ message: string }> { | |
| try { | |
| const { data } = await axios.post<{ message: string }>( | |
| `${API_BASE}/auth/forgot-password`, | |
| payload, | |
| ) | |
| return data | |
| } catch (err) { | |
| normalizeError(err) | |
| } | |
| } | |