fix: dublicate api calls fixed

This commit is contained in:
2026-02-20 20:38:16 +03:30
parent 74f2a82a0e
commit f641409d8a
2 changed files with 97 additions and 44 deletions
+38 -21
View File
@@ -4,6 +4,9 @@ interface ApiOptions extends RequestInit {
token?: string;
}
// Simple in-memory cache for ongoing requests
const pendingRequests = new Map();
class ApiClient {
private async request<T>(
endpoint: string,
@@ -24,17 +27,34 @@ class ApiClient {
headers['Authorization'] = `Bearer ${token}`;
}
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...fetchOptions,
headers,
});
// Create a unique key for this request
const requestKey = `${fetchOptions.method || 'GET'}-${endpoint}-${JSON.stringify(options.body)}`;
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(error.message || 'API request failed');
// Check if there's already a pending request with the same key
if (pendingRequests.has(requestKey)) {
console.log('Deduplicating request:', endpoint);
return pendingRequests.get(requestKey);
}
return response.json();
// Make the request
const promise = fetch(`${API_BASE_URL}${endpoint}`, {
...fetchOptions,
headers,
}).then(async (response) => {
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(error.message || 'API request failed');
}
return response.json();
}).finally(() => {
// Clean up after request completes
pendingRequests.delete(requestKey);
});
// Store the promise
pendingRequests.set(requestKey, promise);
return promise;
}
async post<T>(endpoint: string, data: any, token?: string): Promise<T> {
@@ -64,17 +84,25 @@ class ApiClient {
});
}
async patch<T>(endpoint: string, data: any, token?: string): Promise<T> {
const body = data instanceof FormData ? data : JSON.stringify(data);
return this.request<T>(endpoint, {
method: 'PATCH',
body,
token,
});
}
async delete<T>(endpoint: string, data?: any, token?: string): Promise<T> {
const options: ApiOptions = {
method: 'DELETE',
token,
};
// Handle DELETE with body if data is provided
if (data) {
options.body = data instanceof FormData ? data : JSON.stringify(data);
// Don't set Content-Type for FormData
if (!(data instanceof FormData)) {
options.headers = {
'Content-Type': 'application/json',
@@ -85,20 +113,9 @@ class ApiClient {
return this.request<T>(endpoint, options);
}
// Convenience method for DELETE with JSON body
async deleteWithBody<T>(endpoint: string, data: any, token?: string): Promise<T> {
return this.delete<T>(endpoint, data, token);
}
async patch<T>(endpoint: string, data: any, token?: string): Promise<T> {
const body = data instanceof FormData ? data : JSON.stringify(data);
return this.request<T>(endpoint, {
method: 'PATCH',
body,
token,
});
}
}
export const apiClient = new ApiClient();