import axios from 'axios' import type { AdminLoginBody, AdminLoginResult } from './types' import { adminHttp } from './http' /** POST /auth/login — 与 `routes/api.php` 中 `v1/admin` 分组一致 */ export async function adminLogin(body: AdminLoginBody): Promise { try { const { data } = await adminHttp.post('/auth/login', body) return unwrapLogin(data) } catch (e) { if (axios.isAxiosError(e)) { const raw = e.response?.data const d = raw && typeof raw === 'object' ? (raw as Record) : {} const message = (typeof d.message === 'string' ? d.message : '') || (d.errors && typeof d.errors === 'object' ? Object.values(d.errors as Record).flat().join('\n') : '') || e.message throw new Error(message || '登录失败') } throw e } } function unwrapLogin(raw: unknown): AdminLoginResult { if (raw && typeof raw === 'object') { const o = raw as Record const data = o.data as Record | undefined const token = (typeof o.token === 'string' ? o.token : undefined) ?? (typeof o.access_token === 'string' ? o.access_token : undefined) ?? (data && typeof data.token === 'string' ? data.token : undefined) if (typeof token === 'string') { const userRaw = o.user ?? o.admin ?? data?.user return { token, user: userRaw as AdminLoginResult['user'], } } } throw new Error('登录响应无效') }