File size: 5,654 Bytes
fcc9e86
6d38211
 
 
 
40ea8fa
 
 
6d38211
 
 
40ea8fa
 
 
6d38211
 
 
fcc9e86
 
 
6d38211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcc9e86
6d38211
 
fcc9e86
6d38211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcc9e86
 
6d38211
 
 
 
 
 
fcc9e86
6d38211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcc9e86
 
6d38211
 
 
 
fcc9e86
6d38211
 
 
 
 
fcc9e86
6d38211
 
40ea8fa
6d38211
 
 
40ea8fa
6d38211
40ea8fa
6d38211
 
 
 
 
fcc9e86
6d38211
 
fcc9e86
 
6d38211
 
fcc9e86
6d38211
 
 
fcc9e86
6d38211
 
 
 
 
9a9ef9d
 
6d38211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcc9e86
 
 
40ea8fa
 
 
 
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
type RequestOptions = RequestInit & {
  params?: Record<string, string>;
  retries?: number;
  retryDelay?: number;
  timeout?: number;
};

interface RequestConfig {
  maxRetries: number;
  retryDelay: number;
  timeout: number;
}

const defaultConfig: RequestConfig = {
  maxRetries: 3,
  retryDelay: 1000,
  timeout: 30000,
};

class ApiClient {
  private config: RequestConfig;

  constructor(config: Partial<RequestConfig> = {}) {
    this.config = { ...defaultConfig, ...config };
  }

  private async request<T>(
    url: string,
    options: RequestOptions = {},
  ): Promise<T> {
    const {
      params,
      headers,
      retries = this.config.maxRetries,
      retryDelay = this.config.retryDelay,
      timeout = this.config.timeout,
      signal,
      ...rest
    } = options;

    // Build URL with query params - handle SSR where window is undefined
    const baseUrl =
      typeof window !== "undefined"
        ? window.location.origin
        : process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
    const urlObj = new URL(url, baseUrl);

    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          urlObj.searchParams.append(key, value);
        }
      });
    }

    // Create abort controller for timeout
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);

    // Combine with existing signal if provided
    const combinedSignal = signal
      ? this.combineSignals(signal, controller.signal)
      : controller.signal;

    let lastError: Error = new Error("Request failed");

    for (let attempt = 0; attempt <= retries; attempt++) {
      try {
        const response = await fetch(urlObj.toString(), {
          headers: {
            "Content-Type": "application/json",
            ...headers,
          },
          signal: combinedSignal,
          ...rest,
        });

        clearTimeout(timeoutId);

        if (!response.ok) {
          // Don't retry on client errors (4xx) except for 429 (rate limit)
          if (
            response.status >= 400 &&
            response.status < 500 &&
            response.status !== 429
          ) {
            let errorMessage = "An error occurred";

            try {
              const errorData = await response.json();

              errorMessage =
                errorData.error || errorData.message || response.statusText;
            } catch {
              errorMessage = response.statusText;
            }
            throw new Error(errorMessage);
          }

          // Retry on 429 (rate limit) or 5xx errors
          if (attempt < retries) {
            await this.delay(retryDelay * Math.pow(2, attempt)); // Exponential backoff
            continue;
          }

          let errorMessage = "An error occurred";

          try {
            const errorData = await response.json();

            errorMessage =
              errorData.error || errorData.message || response.statusText;
          } catch {
            errorMessage = response.statusText;
          }
          throw new Error(errorMessage);
        }

        // Handle empty responses (e.g. 204 No Content)
        if (response.status === 204) {
          return {} as T;
        }

        try {
          return await response.json();
        } catch {
          // Fallback if response is not JSON
          return {} as T;
        }
      } catch (error) {
        clearTimeout(timeoutId);

        if (error instanceof Error && error.name === "AbortError") {
          throw new Error("Request timeout");
        }

        lastError = error instanceof Error ? error : new Error(String(error));

        // Retry on network errors
        if (attempt < retries && this.isNetworkError(error)) {
          await this.delay(retryDelay * Math.pow(2, attempt));
          continue;
        }

        throw lastError;
      }
    }

    throw lastError;
  }

  private delay(ms: number): Promise<void> {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  private isNetworkError(error: unknown): boolean {
    if (error instanceof TypeError) {
      return (
        error.message.includes("fetch") || error.message.includes("network")
      );
    }

    return false;
  }

  private combineSignals(
    signal1: AbortSignal,
    signal2: AbortSignal,
  ): AbortSignal {
    const controller = new AbortController();

    const abort = () => controller.abort();

    signal1.addEventListener("abort", abort);
    signal2.addEventListener("abort", abort);

    return controller.signal;
  }

  get<T>(url: string, options?: RequestOptions) {
    return this.request<T>(url, { ...options, method: "GET" });
  }

  post<T>(url: string, body: unknown, options?: RequestOptions) {
    return this.request<T>(url, {
      ...options,
      method: "POST",
      body: JSON.stringify(body),
    });
  }

  put<T>(url: string, body: unknown, options?: RequestOptions) {
    return this.request<T>(url, {
      ...options,
      method: "PUT",
      body: JSON.stringify(body),
    });
  }

  patch<T>(url: string, body: unknown, options?: RequestOptions) {
    return this.request<T>(url, {
      ...options,
      method: "PATCH",
      body: JSON.stringify(body),
    });
  }

  delete<T>(url: string, body?: unknown, options?: RequestOptions) {
    return this.request<T>(url, {
      ...options,
      method: "DELETE",
      body: body ? JSON.stringify(body) : undefined,
    });
  }
}

export const api = new ApiClient();

// Export for custom configuration
export { ApiClient };
export type { RequestOptions };