49 lines
1.1 KiB
TypeScript
Executable File
49 lines
1.1 KiB
TypeScript
Executable File
const BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080';
|
|
|
|
type ApiResponse<T> = {
|
|
data?: T;
|
|
error?: string;
|
|
message?: string;
|
|
};
|
|
|
|
import { redirect } from 'next/navigation';
|
|
|
|
export async function fetchServerAPI<T>(
|
|
endpoint: string,
|
|
token: string,
|
|
method: string = 'GET',
|
|
body?: object
|
|
): Promise<ApiResponse<T>> {
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
Authorization: `Bearer ${token}`
|
|
};
|
|
|
|
const response = await fetch(`${BASE_URL}${endpoint}`, {
|
|
method,
|
|
headers,
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
next: { tags: [endpoint] }
|
|
});
|
|
|
|
if (!response.ok) {
|
|
if (response.status == 401) {
|
|
redirect('/login?expired=true');
|
|
}
|
|
let message = response.statusText;
|
|
try {
|
|
const body = await response.json();
|
|
message = body?.error ?? body?.message ?? message;
|
|
} catch {
|
|
// non-JSON error body, keep statusText
|
|
}
|
|
throw new Error(message);
|
|
}
|
|
|
|
if (response.headers.get('Content-Type')?.includes('application/json')) {
|
|
return { data: await response.json() };
|
|
}
|
|
|
|
return { message: await response.text() };
|
|
}
|