38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
export const browserApiBase = process.env.NEXT_PUBLIC_API_BASE_URL || "/api/v1";
|
|
const internalApiBase = process.env.INTERNAL_API_URL || "http://api:4000/api/v1";
|
|
|
|
export async function serverFetch<T>(path: string): Promise<T> {
|
|
const response = await fetch(`${internalApiBase}${path}`, {
|
|
cache: "no-store"
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`API error: ${response.status}`);
|
|
}
|
|
|
|
return response.json() as Promise<T>;
|
|
}
|
|
|
|
export async function browserFetch<T>(path: string, options?: RequestInit): Promise<T> {
|
|
const headers = new Headers(options?.headers);
|
|
const isFormData = typeof FormData !== "undefined" && options?.body instanceof FormData;
|
|
if (options?.body && !isFormData && !headers.has("Content-Type")) {
|
|
headers.set("Content-Type", "application/json");
|
|
}
|
|
|
|
const response = await fetch(`${browserApiBase}${path}`, {
|
|
...options,
|
|
credentials: "include",
|
|
cache: "no-store",
|
|
headers
|
|
});
|
|
|
|
const data = await response.json().catch(() => ({}));
|
|
if (!response.ok) {
|
|
const error = new Error(data.error || `Request failed: ${response.status}`) as Error & { status?: number };
|
|
error.status = response.status;
|
|
throw error;
|
|
}
|
|
return data as T;
|
|
}
|