update api fetch client
This commit is contained in:
@@ -1,14 +1,27 @@
|
||||
import { logout } from '@/lib/auth/server';
|
||||
import { cookies } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export async function clearAuthAndRedirect(to = '/login') {
|
||||
const c = await cookies();
|
||||
c.delete('session');
|
||||
c.delete('refresh');
|
||||
redirect(to);
|
||||
}
|
||||
|
||||
const BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080';
|
||||
|
||||
type ApiResponse<T> = {
|
||||
data?: T;
|
||||
error?: string;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
export async function fetchServerAPI<T>(
|
||||
endpoint: string,
|
||||
token: string,
|
||||
method: string = 'GET',
|
||||
body?: object
|
||||
): Promise<T> {
|
||||
): Promise<ApiResponse<T>> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
@@ -22,8 +35,8 @@ export async function fetchServerAPI<T>(
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status == 401) {
|
||||
await logout();
|
||||
redirect('/login');
|
||||
clearAuthAndRedirect();
|
||||
return { error: 'unauthorized' };
|
||||
}
|
||||
throw new Error(
|
||||
`API Error: ${response.statusText} - ${method} - ${BASE_URL}${endpoint} - ${token}`
|
||||
@@ -31,8 +44,8 @@ export async function fetchServerAPI<T>(
|
||||
}
|
||||
|
||||
if (response.headers.get('Content-Type')?.includes('application/json')) {
|
||||
return response.json();
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
return response.text() as T;
|
||||
return { message: await response.text() };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user