2026-07-30 14:16:58 +08:00
|
|
|
|
/** 配送点后台 HTTP 客户端,使用独立 API 前缀和 JWT 存储键。 */
|
2026-07-31 11:33:28 +08:00
|
|
|
|
import { getToken } from '@/utils/auth';
|
2026-07-30 14:16:58 +08:00
|
|
|
|
|
2026-07-31 11:33:28 +08:00
|
|
|
|
const apiBaseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:12426/heqi/delivery/v1';
|
2026-07-30 14:16:58 +08:00
|
|
|
|
|
|
|
|
|
|
export type PageResult<T> = { total: number; list: T[] };
|
|
|
|
|
|
|
2026-08-22 19:49:28 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 发送配送点后台请求。
|
|
|
|
|
|
* 参数:path 为 API 相对路径,init 为标准 Fetch 请求选项。
|
|
|
|
|
|
* 返回值:统一响应中的 details;网络、协议或业务失败时抛出可读错误。
|
|
|
|
|
|
*/
|
2026-07-30 14:16:58 +08:00
|
|
|
|
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
2026-07-31 11:33:28 +08:00
|
|
|
|
const token = getToken();
|
2026-07-30 14:16:58 +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-08-22 19:49:28 +08:00
|
|
|
|
const responseText = await response.text();
|
|
|
|
|
|
let payload: { code?: number; message?: string; details?: T };
|
|
|
|
|
|
try {
|
|
|
|
|
|
payload = responseText ? JSON.parse(responseText) : {};
|
|
|
|
|
|
} catch {
|
|
|
|
|
|
// 网关、代理和不存在的路由可能返回纯文本,不能把底层 JSON 异常暴露给用户。
|
|
|
|
|
|
if (!response.ok) throw new Error(`请求失败(HTTP ${response.status})`);
|
|
|
|
|
|
throw new Error('服务器返回了无法识别的数据格式');
|
|
|
|
|
|
}
|
2026-07-30 14:16:58 +08:00
|
|
|
|
if (!response.ok || payload.code !== 0) throw new Error(payload.message || '请求失败');
|
|
|
|
|
|
return payload.details as T;
|
|
|
|
|
|
}
|