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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
|
interface ApiResponse<T> { success: boolean; data: T; message: string; timestamp: number; }
interface PaginatedData<T> { items: T[]; total: number; page: number; pageSize: number; totalPages: number; }
class ApiError extends Error { constructor( public statusCode: number, public errorMessage: string, public details?: unknown ) { super(errorMessage); this.name = "ApiError"; } }
interface RequestConfig { headers?: Record<string, string>; params?: Record<string, string | number | boolean>; timeout?: number; signal?: AbortSignal; }
class HttpClient { private baseUrl: string; private defaultHeaders: Record<string, string>;
constructor(baseUrl: string, defaultHeaders: Record<string, string> = {}) { this.baseUrl = baseUrl; this.defaultHeaders = { "Content-Type": "application/json", ...defaultHeaders, }; }
setAuthToken(token: string): void { this.defaultHeaders["Authorization"] = `Bearer ${token}`; }
private buildUrl(path: string, params?: Record<string, string | number | boolean>): string { const url = new URL(path, this.baseUrl); if (params) { Object.entries(params).forEach(([key, value]) => { url.searchParams.set(key, String(value)); }); } return url.toString(); }
private async request<T>( method: string, path: string, body?: unknown, config?: RequestConfig ): Promise<ApiResponse<T>> { const url = this.buildUrl(path, config?.params); const headers = { ...this.defaultHeaders, ...config?.headers, };
try { const response = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined, signal: config?.signal, });
const data = await response.json();
if (!response.ok) { throw new ApiError( response.status, data.message || response.statusText, data ); }
return data as ApiResponse<T>; } catch (error) { if (error instanceof ApiError) { throw error; } if (error instanceof DOMException && error.name === "AbortError") { throw new ApiError(0, "请求被取消"); } throw new ApiError(0, "网络连接失败", error); } }
async get<T>(path: string, config?: RequestConfig): Promise<ApiResponse<T>> { return this.request<T>("GET", path, undefined, config); }
async post<T, B = unknown>(path: string, body: B, config?: RequestConfig): Promise<ApiResponse<T>> { return this.request<T>("POST", path, body, config); }
async put<T, B = unknown>(path: string, body: B, config?: RequestConfig): Promise<ApiResponse<T>> { return this.request<T>("PUT", path, body, config); }
async patch<T, B = unknown>(path: string, body: B, config?: RequestConfig): Promise<ApiResponse<T>> { return this.request<T>("PATCH", path, body, config); }
async delete<T>(path: string, config?: RequestConfig): Promise<ApiResponse<T>> { return this.request<T>("DELETE", path, undefined, config); } }
interface User { id: number; name: string; email: string; role: "admin" | "editor" | "viewer"; avatar?: string; createdAt: string; updatedAt: string; }
type CreateUserInput = Omit<User, "id" | "createdAt" | "updatedAt">;
type UpdateUserInput = Partial<Omit<User, "id" | "createdAt" | "updatedAt">>;
interface Post { id: number; title: string; content: string; authorId: number; tags: string[]; publishedAt?: string; createdAt: string; }
type CreatePostInput = Omit<Post, "id" | "createdAt">;
class UserService { private client: HttpClient;
constructor(client: HttpClient) { this.client = client; }
async getUsers(page: number = 1, pageSize: number = 10) { return this.client.get<PaginatedData<User>>("/api/users", { params: { page, pageSize } }); }
async getUserById(id: number) { return this.client.get<User>(`/api/users/${id}`); }
async searchUsers(query: string, role?: User["role"]) { return this.client.get<User[]>("/api/users/search", { params: { q: query, ...(role && { role }) } }); }
async createUser(input: CreateUserInput) { return this.client.post<User, CreateUserInput>("/api/users", input); }
async updateUser(id: number, input: UpdateUserInput) { return this.client.patch<User, UpdateUserInput>(`/api/users/${id}`, input); }
async deleteUser(id: number) { return this.client.delete<null>(`/api/users/${id}`); } }
async function main() { const client = new HttpClient("https://api.example.com"); client.setAuthToken("my-jwt-token"); const userService = new UserService(client);
try { const usersResponse = await userService.getUsers(1, 20); console.log(`共 ${usersResponse.data.total} 个用户`); console.log(`当前页 ${usersResponse.data.page}/${usersResponse.data.totalPages}`); usersResponse.data.items.forEach(user => { console.log(`${user.name} (${user.role}) - ${user.email}`); });
const newUser = await userService.createUser({ name: "Alice", email: "alice@example.com", role: "editor", }); console.log(`创建成功,用户 ID: ${newUser.data.id}`);
await userService.updateUser(newUser.data.id, { name: "Alice Updated", });
const user = await userService.getUserById(newUser.data.id); console.log(`更新后: ${user.data.name}`);
await userService.deleteUser(newUser.data.id); console.log("用户已删除");
} catch (error) { if (error instanceof ApiError) { console.error(`API 错误 [${error.statusCode}]: ${error.errorMessage}`); if (error.statusCode === 401) { console.log("请重新登录"); } else if (error.statusCode === 404) { console.log("资源不存在"); } else if (error.statusCode >= 500) { console.log("服务器内部错误,请稍后重试"); } } else if (error instanceof Error) { console.error(`未知错误: ${error.message}`); } } }
main();
|