34 lines
860 B
TypeScript
34 lines
860 B
TypeScript
import { getAuthHeaders } from './auth-headers';
|
|
|
|
const API_BASE =
|
|
process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
|
|
|
|
export async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
|
|
// Använd alltid relativ path i webbläsaren för att undvika mixed content
|
|
const isServer = typeof window === 'undefined';
|
|
const url = isServer
|
|
? (path.startsWith('http') ? path : `${API_BASE}${path}`)
|
|
: path;
|
|
|
|
const authHeaders = isServer ? await getAuthHeaders() : {};
|
|
|
|
const res = await fetch(url, {
|
|
...init,
|
|
cache: 'no-store',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...authHeaders,
|
|
...(init?.headers || {}),
|
|
},
|
|
});
|
|
|
|
if (!res.ok) {
|
|
const text = await res.text();
|
|
throw new Error(`API ${res.status}: ${text}`);
|
|
}
|
|
|
|
return res.json();
|
|
}
|
|
|
|
export { API_BASE };
|