Refactor
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import { fetchData } from '@/lib/data-service';
|
||||
|
||||
export const apiRequest = async <T = any>(endpoint: string, method: string = "GET", body?: T | null) => {
|
||||
try {
|
||||
if (typeof document === "undefined") {
|
||||
@@ -10,7 +12,6 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
|
||||
?.split("=")[1];
|
||||
|
||||
if (!authToken){
|
||||
// go to /login
|
||||
document.location.href = "/login";
|
||||
throw new Error("No authentication token found");
|
||||
}
|
||||
@@ -32,16 +33,16 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
|
||||
const API_URL = process.env.NEXT_PUBLIC_API_URL;
|
||||
if (!API_URL) throw new Error("NEXT_PUBLIC_API_URL is not set in environment variables");
|
||||
|
||||
const res = await fetch(`${API_URL}${endpoint}`, options);
|
||||
const res = await fetchData(`${API_URL}${endpoint}`, options);
|
||||
|
||||
if (!res.ok) {
|
||||
if (!res) {
|
||||
const errorResponse = await res.json().catch(() => null);
|
||||
const errorMessage = errorResponse?.error || res.statusText || "Unknown error";
|
||||
throw new Error(`Failed to ${method} ${endpoint}: ${errorMessage}`);
|
||||
}
|
||||
|
||||
// ✅ Return JSON response
|
||||
return await res.json();
|
||||
return res;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
console.error(`🚨 API Request Error: ${error.message}`);
|
||||
|
||||
Reference in New Issue
Block a user