slight cleanup

This commit is contained in:
g
2025-02-07 19:30:49 +00:00
parent 40635ae667
commit 8900bbcc76
11 changed files with 438 additions and 477 deletions

View File

@@ -1,43 +1,46 @@
// ✅ Client-Safe API Helper
export const fetchWithAuthClient = async <T = any>(
/**
* Client-side API utilities with authentication handling
*/
const getAuthToken = (): string | null => {
const token = document.cookie
.split('; ')
.find(row => row.startsWith('Authorization='))
?.split('=')[1];
return token || null; // Return null instead of throwing an error
};
export const fetchClient = async <T = unknown>(
endpoint: string,
method: string = "GET",
body?: unknown
options: RequestInit = {}
): Promise<T> => {
try {
// ✅ Get auth token from cookies (Client-Safe)
const authToken = document.cookie
.split("; ")
.find((row) => row.startsWith("Authorization="))
?.split("=")[1];
if (!authToken) throw new Error("No authentication token found");
const options: RequestInit = {
method,
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
credentials: "include",
};
if (body) {
options.body = JSON.stringify(body);
const authToken = getAuthToken();
if (!authToken) {
console.warn("No authentication token found. Redirecting to login...");
window.location.href = "/login";
return Promise.reject("Unauthorized");
}
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`,
options
);
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authToken}`,
...options.headers,
},
credentials: 'include',
});
if (!res.ok) {
throw new Error(`Failed to fetch: ${endpoint} (${res.status})`);
const errorData = await res.json();
throw new Error(errorData.message || `Request failed: ${res.statusText}`);
}
return await res.json();
return res.json();
} catch (error) {
console.error("API request error:", error);
console.error(`API request to ${endpoint} failed:`, error);
throw error;
}
};
};