Files
ember-market-frontend/lib/client-utils.ts
2025-03-24 13:43:42 +00:00

47 lines
1.3 KiB
TypeScript

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<T = any>(url: string, options: RequestInit = {}): Promise<T> {
try {
// Create headers with authentication
const headers = createApiHeaders(null, options.headers as Record<string, string>);
// Normalize URL to ensure it uses the Next.js API proxy
const fullUrl = normalizeApiUrl(url);
const res = await fetch(fullUrl, {
...options,
headers,
credentials: 'include',
});
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);
}
// Handle 204 No Content responses
if (res.status === 204) {
return {} as T;
}
return await 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];
}