Files
platforms/frontend/platform_admin/src/api/http.ts

62 lines
1.8 KiB
TypeScript
Raw Normal View History

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';
2026-07-27 00:18:42 +08:00
export const tokenStorageKey = 'token';
export type PageResult<T> = { total: number; list: T[] };
/** 保留 HTTP 状态,供独立页面区分无权限、不存在和普通请求错误。 */
export class ApiError extends Error {
constructor(
message: string,
public readonly status: number,
) {
super(message);
this.name = 'ApiError';
}
}
// 将后端 SDK 的通用英文错误转换为面向用户的中文提示。
const API_ERROR_MESSAGES: Record<string, string> = {
'Invalid Argument': '请求参数不正确,请检查填写内容',
'Record Not Found': '记录不存在',
'Permission Denied': '无权访问该记录',
};
// 优先保留后端提供的具体中文信息,仅翻译已知的通用英文错误。
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('无法连接服务器,请确认服务已启动');
}
const payload = (await response.json()) as {
code?: number;
message?: string;
details?: T;
};
if (!response.ok || payload.code !== 0) {
throw new ApiError(
localizeApiErrorMessage(payload.message),
response.status,
);
}
2026-07-27 00:18:42 +08:00
return payload.details as T;
}