2026-07-27 00:18:42 +08:00
|
|
|
/** 平台总后台的共享 HTTP 客户端,统一处理响应体和 JWT 请求头。 */
|
|
|
|
|
const apiBaseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:12426/heqi/platform/v1';
|
|
|
|
|
|
|
|
|
|
export const tokenStorageKey = 'token';
|
|
|
|
|
|
|
|
|
|
export type PageResult<T> = { total: number; list: T[] };
|
|
|
|
|
|
2026-08-10 19:42:04 +08:00
|
|
|
// 将后端 SDK 的通用英文错误转换为面向用户的中文提示。
|
|
|
|
|
const API_ERROR_MESSAGES: Record<string, string> = {
|
|
|
|
|
'Invalid Argument': '请求参数不正确,请检查填写内容',
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// 优先保留后端提供的具体中文信息,仅翻译已知的通用英文错误。
|
|
|
|
|
function localizeApiErrorMessage(message?: string) {
|
|
|
|
|
if (!message) return '请求失败';
|
|
|
|
|
return API_ERROR_MESSAGES[message.trim()] ?? message;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-27 00:18:42 +08:00
|
|
|
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|
|
|
|
const token = localStorage.getItem(tokenStorageKey);
|
2026-07-29 17:32:24 +08:00
|
|
|
let response: Response;
|
|
|
|
|
try {
|
|
|
|
|
response = await fetch(`${apiBaseURL}${path}`, {
|
|
|
|
|
...init,
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
...(token ? { Authorization: token } : {}),
|
|
|
|
|
...(init?.headers ?? {}),
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
} catch {
|
|
|
|
|
throw new Error('无法连接服务器,请确认服务已启动');
|
|
|
|
|
}
|
2026-07-27 00:18:42 +08:00
|
|
|
const payload = (await response.json()) as { code?: number; message?: string; details?: T };
|
2026-08-10 19:42:04 +08:00
|
|
|
if (!response.ok || payload.code !== 0) {
|
|
|
|
|
throw new Error(localizeApiErrorMessage(payload.message));
|
|
|
|
|
}
|
2026-07-27 00:18:42 +08:00
|
|
|
return payload.details as T;
|
|
|
|
|
}
|