50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
/**
|
|
* Simple client-side fetch function for making API calls with Authorization header.
|
|
*/
|
|
export async function clientFetch(url: string, options: RequestInit = {}): Promise<any> {
|
|
try {
|
|
const authToken = document.cookie
|
|
.split('; ')
|
|
.find(row => row.startsWith('Authorization='))
|
|
?.split('=')[1] || localStorage.getItem('Authorization');
|
|
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
|
|
...options.headers,
|
|
};
|
|
|
|
// 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) throw new Error(`Request failed: ${res.statusText}`);
|
|
|
|
return res.json();
|
|
} catch (error) {
|
|
console.error(`Client fetch error at ${url}:`, error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get a cookie value by name
|
|
*/
|
|
export function getCookie(name: string): string | undefined {
|
|
return document.cookie
|
|
.split('; ')
|
|
.find(row => row.startsWith(`${name}=`))
|
|
?.split('=')[1];
|
|
} |