Refactor
This commit is contained in:
@@ -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;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user