hmmmammamam
This commit is contained in:
@@ -1,41 +1,38 @@
|
||||
import { normalizeApiUrl, getAuthToken, createApiHeaders } from './api-utils';
|
||||
|
||||
/**
|
||||
* Simple client-side fetch function for making API calls with Authorization header.
|
||||
* Ensures all requests go through the Next.js API proxy.
|
||||
*/
|
||||
export async function clientFetch(url: string, options: RequestInit = {}): Promise<any> {
|
||||
export async function clientFetch<T = any>(url: string, options: RequestInit = {}): Promise<T> {
|
||||
try {
|
||||
const authToken = document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('Authorization='))
|
||||
?.split('=')[1] || localStorage.getItem('Authorization');
|
||||
// Create headers with authentication
|
||||
const headers = createApiHeaders(null, options.headers as Record<string, string>);
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
|
||||
...options.headers,
|
||||
};
|
||||
// Normalize URL to ensure it uses the Next.js API proxy
|
||||
const fullUrl = normalizeApiUrl(url);
|
||||
|
||||
const res = await fetch(fullUrl, {
|
||||
...options,
|
||||
headers,
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
// Always use the Next.js API proxy for consistent routing
|
||||
// Format the URL to ensure it has the /api prefix
|
||||
let fullUrl;
|
||||
if (url.startsWith('/api/')) {
|
||||
fullUrl = url; // Already has /api/ prefix
|
||||
} else {
|
||||
// Add /api prefix if not already present
|
||||
const cleanUrl = url.startsWith('/') ? url : `/${url}`;
|
||||
fullUrl = `/api${cleanUrl}`;
|
||||
}
|
||||
|
||||
const res = await fetch(fullUrl, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({}));
|
||||
const errorMessage = errorData.message || errorData.error || `Request failed: ${res.status} ${res.statusText}`;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
if (!res.ok) throw new Error(`Request failed: ${res.statusText}`);
|
||||
// Handle 204 No Content responses
|
||||
if (res.status === 204) {
|
||||
return {} as T;
|
||||
}
|
||||
|
||||
return res.json();
|
||||
return await res.json();
|
||||
} catch (error) {
|
||||
console.error(`Client fetch error at ${url}:`, error);
|
||||
throw error;
|
||||
console.error(`Client fetch error at ${url}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user