client.ts
4.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import axios, { type AxiosRequestConfig, type AxiosError } from 'axios';
export interface ApiResponse<T> {
code: number;
message: string;
data: T;
trace_id?: string;
}
export interface PaginatedResponse<T> {
list: T[];
page: number;
page_size: number;
total: number;
}
export class ApiError extends Error {
constructor(message: string, public code: number) {
super(message);
this.name = 'ApiError';
}
}
export function isApiError(error: unknown): error is ApiError {
return error instanceof ApiError;
}
function getErrorMessageFromAxiosError(error: { response?: { status: number; data?: { message?: string } }; code?: string; message?: string }): string {
if (error.code === 'ERR_NETWORK' || error.message === 'Network Error') {
return '网络错误,请检查网络连接';
}
if (error.code === 'ECONNABORTED' || (error.message?.includes('timeout') ?? false)) {
return '请求超时,请稍后重试';
}
if (error.response) {
const responseData = error.response.data;
if (responseData?.message) {
return responseData.message;
}
return `HTTP 错误: ${error.response.status}`;
}
return error.message || '请求失败';
}
interface ApiClientConfig {
baseURL?: string;
}
interface ApiRuntimeEnv {
MODE?: string;
DEV?: boolean;
VITE_API_BASE_URL?: string;
}
const DEV_API_BASE_URL = '/api/v1';
const SAME_ORIGIN_API_BASE_URL = '/backend/api/v1';
export function resolveApiBaseURL(env: ApiRuntimeEnv = import.meta.env): string {
if (env.VITE_API_BASE_URL) {
return env.VITE_API_BASE_URL;
}
if (env.DEV || env.MODE === 'development') {
return DEV_API_BASE_URL;
}
return SAME_ORIGIN_API_BASE_URL;
}
export function createApiClient(config?: ApiClientConfig) {
const baseURL = config?.baseURL ?? resolveApiBaseURL();
// 不在 axios.create 设置默认 Content-Type,让 axios 自动检测:
// - FormData 自动设置为 multipart/form-data; boundary=...
// - 其他数据需要在请求时显式设置 Content-Type
const axiosInstance = axios.create({
baseURL,
timeout: 30000,
});
async function request<T>(requestConfig: AxiosRequestConfig): Promise<T> {
try {
const response = await axiosInstance.request<ApiResponse<T>>(requestConfig);
const apiResponse = response.data;
if (apiResponse.code === 200 || apiResponse.code === 201) {
return apiResponse.data;
}
throw new ApiError(apiResponse.message || '请求失败', apiResponse.code);
} catch (error) {
if (isApiError(error)) {
throw error;
}
// Check if error looks like an AxiosError (has response property)
const axiosLikeError = error as { response?: { status: number; data?: { message?: string } }; code?: string; message?: string };
if (axiosLikeError.response || axiosLikeError.code === 'ERR_NETWORK' || axiosLikeError.code === 'ECONNABORTED') {
const message = getErrorMessageFromAxiosError(axiosLikeError);
throw new ApiError(message, axiosLikeError.response?.status ?? 0);
}
throw new ApiError((error as Error).message || '请求失败', 0);
}
}
function get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
return request<T>({ ...config, method: 'GET', url });
}
function post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {
// FormData: 不设置 Content-Type,让 axios 自动生成 multipart/form-data; boundary=...
// 其他数据: 显式设置 Content-Type: application/json
const headers = data instanceof FormData
? { ...config?.headers }
: { ...config?.headers, 'Content-Type': 'application/json' };
return request<T>({ ...config, method: 'POST', url, data, headers });
}
function put<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {
// FormData: 不设置 Content-Type,让 axios 自动生成 multipart/form-data; boundary=...
// 其他数据: 显式设置 Content-Type: application/json
const headers = data instanceof FormData
? { ...config?.headers }
: { ...config?.headers, 'Content-Type': 'application/json' };
return request<T>({ ...config, method: 'PUT', url, data, headers });
}
function del<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
return request<T>({ ...config, method: 'DELETE', url });
}
return {
request,
get,
post,
put,
delete: del,
axiosInstance,
};
}
export const apiClient = createApiClient();