-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_api.patch
More file actions
387 lines (374 loc) · 24.6 KB
/
diff_api.patch
File metadata and controls
387 lines (374 loc) · 24.6 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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
diff --git a/admin/src/lib/api.ts b/admin/src/lib/api.ts
index f701c8aa..f2a605af 100644
--- a/admin/src/lib/api.ts
+++ b/admin/src/lib/api.ts
@@ -1,88 +1,319 @@
-const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
-const ADMIN_API_KEY = import.meta.env.VITE_ADMIN_API_KEY;
+import { clearTokens as clearStoredTokens, readAccessToken, readRefreshToken, writeTokens } from './authStorage';
-interface ApiConfig {
- baseURL?: string;
+const DEFAULT_BASE_URL = (import.meta.env.VITE_API_BASE_URL as string | undefined) ?? '';
+const DEFAULT_API_KEY = (import.meta.env.VITE_ADMIN_API_KEY as string | undefined) ?? '';
+
+export interface ApiClientConfig {
+ baseUrl?: string;
+ apiKey?: string;
+ fetchImpl?: typeof fetch;
+}
+
+export interface ApiRequestOptions extends Omit<RequestInit, 'headers'> {
headers?: Record<string, string>;
}
-class ApiClient {
- private config: ApiConfig;
-
- constructor(config: ApiConfig = {}) {
- this.config = {
- baseURL: config.baseURL || API_BASE_URL,
- headers: {
- 'Content-Type': 'application/json',
- 'X-API-Key': ADMIN_API_KEY || '',
- ...config.headers,
- },
- };
- }
-
- private async request<T>(
- endpoint: string,
- options: RequestInit = {}
- ): Promise<T> {
- const url = `${this.config.baseURL}${endpoint}`;
-
- const response = await fetch(url, {
- ...options,
- headers: {
- ...this.config.headers,
- ...options.headers,
- },
- });
+export interface ApiErrorInit {
+ status: number;
+ statusText: string;
+ url: string;
+ data?: unknown;
+}
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.detail || `HTTP ${response.status}: ${response.statusText}`);
+export class ApiError extends Error {
+ public readonly status: number;
+ public readonly statusText: string;
+ public readonly url: string;
+ public readonly data?: unknown;
+
+ constructor(message: string, init: ApiErrorInit) {
+ super(message);
+ this.name = 'ApiError';
+ this.status = init.status;
+ this.statusText = init.statusText;
+ this.url = init.url;
+ this.data = init.data;
+ }
+}
+
+const isFormData = (value: unknown): value is FormData =>
+ typeof FormData !== 'undefined' && value instanceof FormData;
+
+const isBlob = (value: unknown): value is Blob =>
+ typeof Blob !== 'undefined' && value instanceof Blob;
+
+const isURLSearchParams = (value: unknown): value is URLSearchParams =>
+ typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams;
+
+const isReadableStream =
+ typeof ReadableStream !== 'undefined'
+ ? (value: unknown): value is ReadableStream<Uint8Array> => value instanceof ReadableStream
+ : (_value: unknown): _value is ReadableStream<Uint8Array> => false;
+
+const isArrayBuffer = (value: unknown): value is ArrayBuffer =>
+ typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer;
+
+const isArrayBufferView = (value: unknown): value is ArrayBufferView =>
+ typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(value as ArrayBufferView);
+
+const redirectToLogin = () => {
+ if (typeof window !== 'undefined') {
+ window.location.replace('/login');
+ }
+};
+
+export class ApiClient {
+ private readonly baseUrl: string;
+ private readonly apiKey: string;
+ private readonly fetchImpl: typeof fetch;
+
+ constructor(config: ApiClientConfig = {}) {
+ const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
+ this.baseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
+ this.apiKey = config.apiKey ?? DEFAULT_API_KEY;
+ this.fetchImpl = config.fetchImpl ?? fetch;
+ }
+
+ private buildUrl(endpoint: string): string {
+ if (endpoint.startsWith('http://') || endpoint.startsWith('https://')) {
+ return endpoint;
+ }
+
+ const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
+ return `${this.baseUrl}${normalizedEndpoint}`;
+ }
+
+ private shouldSerializeBody(method: string): boolean {
+ return method !== 'GET' && method !== 'HEAD';
+ }
+
+ private prepareBody(body: unknown, method: string): BodyInit | undefined {
+ if (!this.shouldSerializeBody(method) || body === undefined || body === null) {
+ return undefined;
}
- const contentType = response.headers.get('content-type');
- if (contentType && contentType.includes('application/json')) {
+ if (
+ isFormData(body) ||
+ isBlob(body) ||
+ isURLSearchParams(body) ||
+ isReadableStream(body) ||
+ isArrayBuffer(body) ||
+ isArrayBufferView(body) ||
+ typeof body === 'string'
+ ) {
+ return body as BodyInit;
+ }
+
+ return JSON.stringify(body);
+ }
+
+ private async parseResponse(response: Response): Promise<unknown> {
+ if (response.status === 204 || response.status === 205) {
+ return undefined;
+ }
+
+ const contentType = response.headers.get('content-type') ?? '';
+ const isJson = contentType.includes('application/json');
+
+ if (isJson) {
return response.json();
}
- return response.text() as unknown as T;
+ return response.text();
}
- async get<T>(endpoint: string): Promise<T> {
- return this.request<T>(endpoint, { method: 'GET' });
+ private getAuthToken(): string | null {
+ return readAccessToken();
}
- async post<T>(endpoint: string, data?: any): Promise<T> {
- return this.request<T>(endpoint, {
- method: 'POST',
- body: data ? JSON.stringify(data) : undefined,
- });
+ private async refreshToken(): Promise<boolean> {
+ const refreshToken = readRefreshToken();
+ if (!refreshToken) {
+ return false;
+ }
+
+ try {
+ const response = await this.fetchImpl(this.buildUrl('/auth/refresh'), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ refresh_token: refreshToken }),
+ });
+
+ if (response.ok) {
+ const tokens = await response.json();
+ writeTokens({ accessToken: tokens.access_token, refreshToken: tokens.refresh_token });
+ return true;
+ }
+ } catch (error) {
+ console.error('Token refresh failed:', error);
+ }
+
+ clearStoredTokens();
+ redirectToLogin();
+ return false;
}
- async put<T>(endpoint: string, data?: any): Promise<T> {
- return this.request<T>(endpoint, {
- method: 'PUT',
- body: data ? JSON.stringify(data) : undefined,
- });
+ private ensureBaseHeaders(headers: Headers, body: unknown, apiKey?: string): void {
+ const token = this.getAuthToken();
+
+ if (token && !apiKey) {
+ headers.set('Authorization', `Bearer ${token}`);
+ } else if (apiKey) {
+ headers.set('X-API-Key', apiKey);
+ }
+
+ if (!isFormData(body)) {
+ headers.set('Content-Type', 'application/json');
+ } else {
+ headers.delete('Content-Type');
+ }
}
- async delete<T>(endpoint: string): Promise<T> {
- return this.request<T>(endpoint, { method: 'DELETE' });
+ private extractErrorMessage(payload: unknown, response: Response): string {
+ if (typeof payload === 'string' && payload.trim()) {
+ return payload;
+ }
+
+ if (payload && typeof payload === 'object') {
+ const candidate =
+ (payload as Record<string, unknown>).detail ??
+ (payload as Record<string, unknown>).message ??
+ (payload as Record<string, unknown>).error ??
+ (payload as Record<string, unknown>).title;
+
+ if (typeof candidate === 'string' && candidate.trim()) {
+ return candidate;
+ }
+ }
+
+ return `HTTP ${response.status}: ${response.statusText}`;
}
- async uploadFile<T>(endpoint: string, file: File): Promise<T> {
- const formData = new FormData();
- formData.append('file', file);
+ async request<T>(endpoint: string, options: ApiRequestOptions = {}): Promise<T> {
+ const method = (options.method ?? 'GET').toUpperCase();
+ const url = this.buildUrl(endpoint);
+ const headers = new Headers(options.headers);
+ const body = this.prepareBody(options.body, method);
+
+ const providedKey =
+ (options.headers &&
+ (options.headers['X-API-Key'] ?? (options.headers['x-api-key'] as string | undefined))) ??
+ undefined;
+ const resolvedApiKey = (providedKey ?? this.apiKey ?? '').trim();
+ const token = this.getAuthToken();
+
+ if (!token && !resolvedApiKey) {
+ throw new ApiError('Authentication required. Please log in or provide API key.', {
+ status: 401,
+ statusText: 'Unauthorized',
+ url,
+ });
+ }
+
+ this.ensureBaseHeaders(headers, options.body, resolvedApiKey);
+
+ let response: Response;
+
+ try {
+ response = await this.fetchImpl(url, {
+ ...options,
+ method,
+ headers,
+ body,
+ });
+ } catch (error) {
+ throw new ApiError('Network request failed', {
+ status: 0,
+ statusText: 'FETCH_ERROR',
+ url,
+ data: error,
+ });
+ }
+
+ if (response.status === 401 && token && !providedKey) {
+ const refreshed = await this.refreshToken();
+ if (refreshed) {
+ const newHeaders = new Headers(options.headers);
+ this.ensureBaseHeaders(newHeaders, options.body);
+
+ try {
+ const retryResponse = await this.fetchImpl(url, {
+ ...options,
+ method,
+ headers: newHeaders,
+ body,
+ });
+
+ if (!retryResponse.ok) {
+ const retryPayload = await this.parseResponse(retryResponse);
+ const message = this.extractErrorMessage(retryPayload, retryResponse);
+ throw new ApiError(message, {
+ status: retryResponse.status,
+ statusText: retryResponse.statusText,
+ url,
+ data: retryPayload,
+ });
+ }
- return this.request<T>(endpoint, {
- method: 'POST',
- body: formData,
- headers: {
- 'X-API-Key': ADMIN_API_KEY || '',
- },
- });
+ return (await this.parseResponse(retryResponse)) as T;
+ } catch (retryError) {
+ if (retryError instanceof ApiError) {
+ throw retryError;
+ }
+ throw new ApiError('Retry request failed', {
+ status: 0,
+ statusText: 'RETRY_ERROR',
+ url,
+ data: retryError,
+ });
+ }
+ }
+
+ throw new ApiError('Authentication failed', {
+ status: 401,
+ statusText: 'Unauthorized',
+ url,
+ });
+ }
+
+ const payload = await this.parseResponse(response);
+
+ if (!response.ok) {
+ const message = this.extractErrorMessage(payload, response);
+ throw new ApiError(message, {
+ status: response.status,
+ statusText: response.statusText,
+ url,
+ data: payload,
+ });
+ }
+
+ return payload as T;
+ }
+
+ get<T>(endpoint: string, options?: Omit<ApiRequestOptions, 'method' | 'body'>): Promise<T> {
+ return this.request<T>(endpoint, { ...options, method: 'GET' });
+ }
+
+ post<T>(endpoint: string, body?: unknown, options?: Omit<ApiRequestOptions, 'method' | 'body'>): Promise<T> {
+ return this.request<T>(endpoint, { ...options, method: 'POST', body });
+ }
+
+ put<T>(endpoint: string, body?: unknown, options?: Omit<ApiRequestOptions, 'method' | 'body'>): Promise<T> {
+ return this.request<T>(endpoint, { ...options, method: 'PUT', body });
+ }
+
+ patch<T>(endpoint: string, body?: unknown, options?: Omit<ApiRequestOptions, 'method' | 'body'>): Promise<T> {
+ return this.request<T>(endpoint, { ...options, method: 'PATCH', body });
+ }
+
+ delete<T>(endpoint: string, options?: Omit<ApiRequestOptions, 'method'>): Promise<T> {
+ return this.request<T>(endpoint, { ...options, method: 'DELETE' });
}
}
export const apiClient = new ApiClient();
-export default apiClient;
\ No newline at end of file
+export const createApiClient = (config?: ApiClientConfig): ApiClient => new ApiClient(config);
+
+export default apiClient;