Update client-service.ts

This commit is contained in:
NotII
2025-03-08 05:53:50 +00:00
parent 9fe457dee7
commit 8635d0fd27

View File

@@ -11,25 +11,65 @@ interface FetchOptions {
headers?: HeadersInit; 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>( export async function fetchClient<T>(
endpoint: string, endpoint: string,
options: FetchOptions = {} options: FetchOptions = {}
): Promise<T> { ): Promise<T> {
const { method = 'GET', body, headers = {}, ...rest } = options; 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'; const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
// Check if endpoint already includes /api // Ensure the endpoint starts with a slash
const apiPrefix = endpoint.includes('/api/') ? '' : '/api'; const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
const url = `${apiUrl}${apiPrefix}${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 = { const fetchOptions: RequestInit = {
method, method,
credentials: 'include', credentials: 'include',
headers: { headers: requestHeaders,
'Content-Type': 'application/json',
...headers,
},
...rest, ...rest,
}; };