Update client-service.ts
This commit is contained in:
@@ -11,25 +11,65 @@ interface FetchOptions {
|
||||
headers?: HeadersInit;
|
||||
}
|
||||
|
||||
// Helper function to get auth token from cookies
|
||||
function getAuthToken(): string | null {
|
||||
if (typeof document === 'undefined') return null; // Guard for SSR
|
||||
|
||||
return document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('Authorization='))
|
||||
?.split('=')[1] || null;
|
||||
}
|
||||
|
||||
export async function fetchClient<T>(
|
||||
endpoint: string,
|
||||
options: FetchOptions = {}
|
||||
): Promise<T> {
|
||||
const { method = 'GET', body, headers = {}, ...rest } = options;
|
||||
|
||||
// Get the base API URL from environment or fallback
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
||||
|
||||
// Check if endpoint already includes /api
|
||||
const apiPrefix = endpoint.includes('/api/') ? '' : '/api';
|
||||
const url = `${apiUrl}${apiPrefix}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`;
|
||||
// Ensure the endpoint starts with a slash
|
||||
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
|
||||
|
||||
// For the specific case of internal-api.inboxi.ng - remove duplicate /api
|
||||
let url;
|
||||
if (apiUrl.includes('internal-api.inboxi.ng')) {
|
||||
// Special case for internal-api.inboxi.ng
|
||||
if (normalizedEndpoint.startsWith('/api/')) {
|
||||
url = `${apiUrl}${normalizedEndpoint.substring(4)}`; // Remove the /api part
|
||||
} else {
|
||||
url = `${apiUrl}${normalizedEndpoint}`;
|
||||
}
|
||||
} else {
|
||||
// Normal case for other environments
|
||||
url = `${apiUrl}${normalizedEndpoint}`;
|
||||
}
|
||||
|
||||
// Get auth token from cookies
|
||||
const authToken = getAuthToken();
|
||||
|
||||
// Prepare headers with authentication if token exists
|
||||
const requestHeaders: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(headers as Record<string, string>),
|
||||
};
|
||||
|
||||
if (authToken) {
|
||||
requestHeaders['Authorization'] = `Bearer ${authToken}`;
|
||||
}
|
||||
|
||||
console.log('API Request:', {
|
||||
url,
|
||||
method,
|
||||
hasAuthToken: !!authToken
|
||||
});
|
||||
|
||||
const fetchOptions: RequestInit = {
|
||||
method,
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...headers,
|
||||
},
|
||||
headers: requestHeaders,
|
||||
...rest,
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user