client.ts
2.18 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
import { ApiResponse, ApiError, isSuccessCode } from './types';
export interface ApiClientOptions {
baseUrl?: string;
}
export interface RequestOptions {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
headers?: Record<string, string>;
body?: unknown;
}
const DEFAULT_BASE_URL = '/api/v1';
export function createApiClient(options: ApiClientOptions = {}) {
const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
async function request<T>(
endpoint: string,
requestOptions: RequestOptions = {}
): Promise<T> {
const { method = 'GET', headers = {}, body } = requestOptions;
const url = `${baseUrl}${endpoint}`;
const fetchOptions: RequestInit = {
method,
headers: {
'Content-Type': 'application/json',
...headers,
},
};
if (body !== undefined && method !== 'GET') {
fetchOptions.body = JSON.stringify(body);
}
try {
const response = await fetch(url, fetchOptions);
const json = (await response.json()) as ApiResponse<T>;
if (!response.ok) {
throw new ApiError(
response.status,
json.message || `HTTP Error: ${response.status}`,
false
);
}
if (!isSuccessCode(json.code)) {
throw new ApiError(json.code, json.message, false);
}
return json.data;
} catch (error) {
if (ApiError.isApiError(error)) {
throw error;
}
// Network error
if (error instanceof TypeError) {
throw new ApiError(0, '网络连接失败', true);
}
throw new ApiError(0, (error as Error).message || '未知错误', false);
}
}
return {
get: <T>(endpoint: string, options?: RequestOptions) =>
request<T>(endpoint, { ...options, method: 'GET' }),
post: <T>(endpoint: string, body: unknown, options?: RequestOptions) =>
request<T>(endpoint, { ...options, method: 'POST', body }),
put: <T>(endpoint: string, body: unknown, options?: RequestOptions) =>
request<T>(endpoint, { ...options, method: 'PUT', body }),
delete: <T>(endpoint: string, options?: RequestOptions) =>
request<T>(endpoint, { ...options, method: 'DELETE' }),
};
}
// Export types
export * from './types';