/** * 接口客户端:统一带上 `Authorization: Bearer ` + `X-Subject-Id`, * 统一处理 `{ ok, data, message }` 结构 * * 后端约定(见 backend/README): * - 成功 `{ ok: true, data }`;失败 `{ ok: false, message, status? }` * - 401 = 令牌缺失/过期/无效 → 清掉本地令牌并跳登录页 * - 400 `status='subject_required'` = 没选主体;403 `status='subject_expired'` = 主体到期 * (这两种由页面自己提示,不清令牌) */ import { clearToken, getToken } from '@/composables/useAuth'; import { getStoredSubjectId } from '@/composables/subjectStorage'; /** 开发时走 Vite 代理(同源 /api),生产时后端同源托管,所以默认空字符串即可 */ const BASE = (import.meta.env.VITE_API_BASE as string | undefined) || ''; export interface ApiResult { ok: boolean; data?: T; message?: string; status?: string; } export class ApiError extends Error { status: number; code?: string; constructor(message: string, status: number, code?: string) { super(message); this.status = status; this.code = code; } } interface RequestOptions { method?: 'GET' | 'POST' | 'PUT' | 'DELETE'; body?: unknown; /** 带上令牌(默认带;登录等公开接口可传 false) */ auth?: boolean; /** 中断信号:长轮询(扫码登录 / 绑定 / 工作台登入)在切面板、关弹窗时要能立刻断开 */ signal?: AbortSignal; } async function request(path: string, options: RequestOptions = {}): Promise { const { method = 'GET', body, auth = true, signal } = options; const headers: Record = {}; if (body !== undefined) headers['Content-Type'] = 'application/json'; if (auth) { const token = getToken(); if (token) headers.Authorization = `Bearer ${token}`; // 主体范围:业务接口都靠这个 header 限定操作范围(没有主体时不带,后端回 subject_required) const subjectId = getStoredSubjectId(); if (subjectId) headers['X-Subject-Id'] = String(subjectId); } const res = await fetch(`${BASE}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal, }); let payload: ApiResult | null = null; try { payload = (await res.json()) as ApiResult; } catch { payload = null; } if (res.status === 401) { clearToken(); throw new ApiError(payload?.message || '登录已过期,请重新登录', 401, payload?.status); } if (!res.ok || !payload || payload.ok === false) { throw new ApiError(payload?.message || `请求失败(${res.status})`, res.status, payload?.status); } return payload.data as T; } export const api = { get: (path: string, options?: Omit) => request(path, { ...options, method: 'GET' }), post: (path: string, body?: unknown, options?: Omit) => request(path, { ...options, method: 'POST', body }), put: (path: string, body?: unknown, options?: Omit) => request(path, { ...options, method: 'PUT', body }), del: (path: string, body?: unknown, options?: Omit) => request(path, { ...options, method: 'DELETE', body }), };