hmmmammamam
This commit is contained in:
@@ -1,32 +1,30 @@
|
||||
import { cookies } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { getServerApiUrl } from './api-utils';
|
||||
|
||||
/**
|
||||
* Server-side fetch wrapper with authentication.
|
||||
* Used in Server Components to make authenticated API requests to the backend.
|
||||
* This uses the SERVER_API_URL environment variable and is different from client-side fetching.
|
||||
*/
|
||||
export async function fetchServer<T = unknown>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
// Get auth token from cookies
|
||||
const cookieStore = cookies();
|
||||
const authToken = cookieStore.get('Authorization')?.value;
|
||||
|
||||
// Redirect to login if not authenticated
|
||||
if (!authToken) redirect('/login');
|
||||
|
||||
// Ensure the endpoint doesn't start with a slash if it's going to be appended to a URL that ends with one
|
||||
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
try {
|
||||
// Make sure we're using a complete URL (protocol + hostname + path)
|
||||
const apiUrl = process.env.SERVER_API_URL || 'https://internal-api.inboxi.ng/api';
|
||||
// Get the complete backend URL using the utility function
|
||||
const url = getServerApiUrl(endpoint);
|
||||
|
||||
// Ensure there's only one slash between the base URL and endpoint
|
||||
const url = apiUrl.endsWith('/')
|
||||
? `${apiUrl}${cleanEndpoint}`
|
||||
: `${apiUrl}/${cleanEndpoint}`;
|
||||
|
||||
console.log(`Making server request to: ${url}`);
|
||||
|
||||
// Make the request with proper auth headers
|
||||
const res = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
@@ -34,13 +32,25 @@ export async function fetchServer<T = unknown>(
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
...options.headers,
|
||||
},
|
||||
cache: 'no-store',
|
||||
cache: 'no-store', // Always fetch fresh data
|
||||
});
|
||||
|
||||
// Handle auth failures
|
||||
if (res.status === 401) redirect('/login');
|
||||
if (!res.ok) throw new Error(`Request failed: ${res.statusText}`);
|
||||
|
||||
// Handle other errors
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({}));
|
||||
const errorMessage = errorData.message || errorData.error || `Request failed: ${res.status} ${res.statusText}`;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
return res.json();
|
||||
// Handle 204 No Content responses
|
||||
if (res.status === 204) {
|
||||
return {} as T;
|
||||
}
|
||||
|
||||
return await res.json();
|
||||
} catch (error) {
|
||||
console.error(`Server request to ${endpoint} failed:`, error);
|
||||
throw error;
|
||||
|
||||
Reference in New Issue
Block a user