nomadro/apps/admin/src/api/client.ts
eric 3e5b7c2098 Monorepo super-optimize: src layout, workspace scripts, docs.
Collapse portal under src/, unify pnpm workspace/scripts, thin VIP topic re-exports, drop orphan vip scaffolds and one-shot scripts, ignore xhs/release, document root commands.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 00:34:04 +08:00

38 lines
1.1 KiB
TypeScript

const TOKEN_KEY = 'nomadro_admin_token'
/** 生产环境走同域 /api 或通过 VITE_API_BASE 指定 */
export const API_BASE = import.meta.env.VITE_API_BASE || ''
export function getToken() {
return localStorage.getItem(TOKEN_KEY) || ''
}
export function setToken(t: string) {
localStorage.setItem(TOKEN_KEY, t)
}
export function clearToken() {
localStorage.removeItem(TOKEN_KEY)
}
export async function api<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(init.headers as Record<string, string> | undefined),
}
const token = getToken()
if (token) headers.Authorization = `Bearer ${token}`
const res = await fetch(`${API_BASE}${path}`, { ...init, headers })
if (res.status === 401) {
clearToken()
if (!path.includes('/login')) window.location.href = '/login'
}
const data = await res.json().catch(() => ({}))
if (!res.ok) {
const err = data as { detail?: string; message?: string }
throw new Error(err.detail || err.message || '请求失败')
}
return data as T
}