30 lines
850 B
TypeScript
30 lines
850 B
TypeScript
/**
|
|
* Shared API helpers for ChronoMind web clients.
|
|
*
|
|
* Provides a common fetch wrapper with auth token injection.
|
|
*/
|
|
|
|
import { getBackendBaseURL } from './product-config';
|
|
|
|
export function getAccessToken(): string | null {
|
|
if (typeof window === 'undefined') return null;
|
|
return localStorage.getItem('chronomind_access_token');
|
|
}
|
|
|
|
export async function apiFetch<T>(path: string, opts?: RequestInit): Promise<T> {
|
|
const token = getAccessToken();
|
|
const res = await fetch(`${getBackendBaseURL()}${path}`, {
|
|
...opts,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
...(opts?.headers ?? {}),
|
|
},
|
|
});
|
|
if (!res.ok) {
|
|
const body = await res.text().catch(() => '');
|
|
throw new Error(`${res.status}: ${body}`);
|
|
}
|
|
return res.json() as Promise<T>;
|
|
}
|