Files
robot-shanghai/src/api/client.ts
T
2026-09-08 14:19:44 +08:00

85 lines
1.6 KiB
TypeScript

/**
* API 客户端配置
* 可以根据项目需求使用 axios、fetch 或其他 HTTP 客户端
*/
import type { ApiError, ApiResponse } from "./client.types";
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "/api";
/**
* 基础请求函数
*/
export async function request<T>(
endpoint: string,
options?: RequestInit,
): Promise<ApiResponse<T>> {
const url = `${API_BASE_URL}${endpoint}`;
try {
const response = await fetch(url, {
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = (await response.json()) as ApiResponse<T>;
return data;
} catch (error) {
throw {
message: error instanceof Error ? error.message : "Unknown error",
code: 500,
} as ApiError;
}
}
/**
* GET 请求
*/
export function get<T>(endpoint: string, options?: RequestInit) {
return request<T>(endpoint, { ...options, method: "GET" });
}
/**
* POST 请求
*/
export function post<T>(
endpoint: string,
data?: unknown,
options?: RequestInit,
) {
return request<T>(endpoint, {
...options,
method: "POST",
body: data ? JSON.stringify(data) : undefined,
});
}
/**
* PUT 请求
*/
export function put<T>(
endpoint: string,
data?: unknown,
options?: RequestInit,
) {
return request<T>(endpoint, {
...options,
method: "PUT",
body: data ? JSON.stringify(data) : undefined,
});
}
/**
* DELETE 请求
*/
export function del<T>(endpoint: string, options?: RequestInit) {
return request<T>(endpoint, { ...options, method: "DELETE" });
}