更新+mock部分
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import type { ApiResponse } from "../types/api";
|
||||
import { getAccessToken } from "./storage";
|
||||
|
||||
const BASE_URL = import.meta.env.VITE_API_BASE_URL ?? "/api";
|
||||
@@ -12,6 +13,14 @@ interface RequestOptions {
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
function isApiResponse(payload: unknown): payload is ApiResponse<unknown> {
|
||||
if (typeof payload !== "object" || payload === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return "code" in payload && "message" in payload && "data" in payload;
|
||||
}
|
||||
|
||||
function buildUrl(path: string) {
|
||||
if (/^https?:\/\//.test(path)) {
|
||||
return path;
|
||||
@@ -57,6 +66,9 @@ async function request<T>(path: string, options: RequestOptions = {}): Promise<T
|
||||
: `Request failed with status ${response.status}`;
|
||||
throw new Error(message);
|
||||
}
|
||||
if (isApiResponse(payload) && payload.code !== 0) {
|
||||
throw new Error(payload.message || `Business request failed with code ${payload.code}`);
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
} finally {
|
||||
|
||||
Reference in New Issue
Block a user