|
1 | | -const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1'; |
| 1 | +const API_BASE_URL = |
| 2 | + process.env.NEXT_PUBLIC_API_URL || process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:3001/api/v1'; |
2 | 3 |
|
3 | | -export async function apiCall(endpoint: string, options: RequestInit = {}) { |
4 | | - const response = await fetch(`${API_BASE_URL}${endpoint}`, { |
5 | | - ...options, |
6 | | - headers: { |
7 | | - 'Content-Type': 'application/json', |
8 | | - ...options.headers, |
9 | | - }, |
10 | | - }); |
| 4 | +const DEFAULT_RETRY_CONFIG: RetryConfig = { |
| 5 | + maxRetries: 3, |
| 6 | + baseDelay: 1000, |
| 7 | + maxDelay: 10000, |
| 8 | + jitter: true, |
| 9 | +}; |
11 | 10 |
|
12 | | - if (!response.ok) { |
13 | | - throw new Error(`API Error: ${response.statusText}`); |
| 11 | +export interface RetryConfig { |
| 12 | + maxRetries: number; |
| 13 | + baseDelay: number; |
| 14 | + maxDelay: number; |
| 15 | + jitter: boolean; |
| 16 | +} |
| 17 | + |
| 18 | +export class ApiError extends Error { |
| 19 | + status: number; |
| 20 | + response: Response; |
| 21 | + data?: unknown; |
| 22 | + |
| 23 | + constructor(message: string, status: number, response: Response, data?: unknown) { |
| 24 | + super(message); |
| 25 | + this.name = 'ApiError'; |
| 26 | + this.status = status; |
| 27 | + this.response = response; |
| 28 | + this.data = data; |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +function shouldRetryStatus(status: number): boolean { |
| 33 | + return status >= 500 || status === 429; |
| 34 | +} |
| 35 | + |
| 36 | +function shouldRetryError(error: unknown): boolean { |
| 37 | + if (error instanceof ApiError) { |
| 38 | + return shouldRetryStatus(error.status); |
| 39 | + } |
| 40 | + |
| 41 | + if ( |
| 42 | + (error instanceof Error && error.name === 'AbortError') || |
| 43 | + (typeof error === 'object' && |
| 44 | + error !== null && |
| 45 | + 'name' in error && |
| 46 | + error.name === 'AbortError') |
| 47 | + ) { |
| 48 | + return false; |
| 49 | + } |
| 50 | + |
| 51 | + return true; |
| 52 | +} |
| 53 | + |
| 54 | +function calculateDelay(attempt: number, config: RetryConfig): number { |
| 55 | + const exponentialDelay = config.baseDelay * Math.pow(2, attempt); |
| 56 | + const delay = Math.min(exponentialDelay, config.maxDelay); |
| 57 | + return config.jitter ? delay * (0.5 + Math.random()) : delay; |
| 58 | +} |
| 59 | + |
| 60 | +function delay(ms: number): Promise<void> { |
| 61 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 62 | +} |
| 63 | + |
| 64 | +function normalizeError(error: unknown): Error { |
| 65 | + if (error instanceof Error) { |
| 66 | + return error; |
| 67 | + } |
| 68 | + |
| 69 | + const message = |
| 70 | + typeof error === 'object' && |
| 71 | + error !== null && |
| 72 | + 'message' in error && |
| 73 | + typeof error.message === 'string' |
| 74 | + ? error.message |
| 75 | + : String(error); |
| 76 | + |
| 77 | + const normalized = new Error(message); |
| 78 | + |
| 79 | + if ( |
| 80 | + typeof error === 'object' && |
| 81 | + error !== null && |
| 82 | + 'name' in error && |
| 83 | + typeof error.name === 'string' |
| 84 | + ) { |
| 85 | + normalized.name = error.name; |
14 | 86 | } |
15 | 87 |
|
16 | | - return response.json(); |
| 88 | + return normalized; |
17 | 89 | } |
18 | 90 |
|
| 91 | +async function parseResponseBody(response: Response): Promise<unknown> { |
| 92 | + const contentType = response.headers.get('content-type') || ''; |
| 93 | + |
| 94 | + if (response.status === 204) { |
| 95 | + return null; |
| 96 | + } |
| 97 | + |
| 98 | + if (contentType.includes('application/json')) { |
| 99 | + return response.json(); |
| 100 | + } |
| 101 | + |
| 102 | + const text = await response.text(); |
| 103 | + return text.length > 0 ? text : null; |
| 104 | +} |
| 105 | + |
| 106 | +function getErrorMessage(statusText: string, data: unknown): string { |
| 107 | + if (data && typeof data === 'object' && 'message' in data && typeof data.message === 'string') { |
| 108 | + return data.message; |
| 109 | + } |
| 110 | + |
| 111 | + if (typeof data === 'string' && data.trim().length > 0) { |
| 112 | + return data; |
| 113 | + } |
| 114 | + |
| 115 | + return `API Error: ${statusText}`; |
| 116 | +} |
| 117 | + |
| 118 | +export async function apiCall<T = unknown>( |
| 119 | + endpoint: string, |
| 120 | + options: RequestInit = {}, |
| 121 | + retryConfig?: Partial<RetryConfig> |
| 122 | +): Promise<T> { |
| 123 | + const config = { ...DEFAULT_RETRY_CONFIG, ...retryConfig }; |
| 124 | + let lastError: Error | undefined; |
| 125 | + |
| 126 | + for (let attempt = 0; attempt <= config.maxRetries; attempt++) { |
| 127 | + try { |
| 128 | + const response = await fetch(`${API_BASE_URL}${endpoint}`, { |
| 129 | + ...options, |
| 130 | + headers: { |
| 131 | + 'Content-Type': 'application/json', |
| 132 | + ...options.headers, |
| 133 | + }, |
| 134 | + }); |
| 135 | + |
| 136 | + const data = await parseResponseBody(response); |
| 137 | + |
| 138 | + if (response.ok) { |
| 139 | + return data as T; |
| 140 | + } |
| 141 | + |
| 142 | + throw new ApiError( |
| 143 | + getErrorMessage(response.statusText, data), |
| 144 | + response.status, |
| 145 | + response, |
| 146 | + data |
| 147 | + ); |
| 148 | + } catch (error) { |
| 149 | + lastError = normalizeError(error); |
| 150 | + |
| 151 | + if (attempt === config.maxRetries || !shouldRetryError(error)) { |
| 152 | + throw lastError; |
| 153 | + } |
| 154 | + |
| 155 | + await delay(calculateDelay(attempt, config)); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + throw lastError || new Error('API call failed after retries'); |
| 160 | +} |
0 commit comments