This commit is contained in:
g
2025-02-07 21:33:13 +00:00
parent 8900bbcc76
commit 891f57d729
50 changed files with 165 additions and 444 deletions

View File

@@ -1,46 +1,32 @@
/**
* Client-side API utilities with authentication handling
* Simple client-side fetch function for making API calls with Authorization header.
*/
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,
options: RequestInit = {}
): Promise<T> => {
export async function clientFetch(url: string, options: RequestInit = {}): Promise<any> {
try {
const authToken = getAuthToken();
if (!authToken) {
console.warn("No authentication token found. Redirecting to login...");
window.location.href = "/login";
return Promise.reject("Unauthorized");
}
const authToken = document.cookie
.split('; ')
.find(row => row.startsWith('Authorization='))
?.split('=')[1] || localStorage.getItem('Authorization');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authToken}`,
...options.headers,
},
credentials: 'include',
});
console.log('authToken', authToken);
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.message || `Request failed: ${res.statusText}`);
}
// Merge Authorization header if token is found
const headers = {
'Content-Type': 'application/json',
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
...options.headers,
};
return res.json();
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${url}`, {
...options,
headers,
});
if (!res.ok) throw new Error(`Request failed: ${res.statusText}`);
return res.json();
} catch (error) {
console.error(`API request to ${endpoint} failed:`, error);
throw error;
console.error(`Client fetch error at ${url}:`, error);
throw error;
}
};
}