CASA-MIL / frontend /src /api /auth.ts
quoctrong's picture
Deploy MRI Pathology Detection App with LFS for all binaries
da8e27d
Raw
History Blame Contribute Delete
2.68 kB
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)
}
}