Files
ember-market-frontend/lib/server-service.ts
2025-03-10 17:56:24 +00:00

96 lines
3.1 KiB
TypeScript

import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
/**
* Gets the base URL for server API requests with proper fallbacks
*/
function getBaseUrl() {
// First check for the specific server API URL environment variable
if (process.env.SERVER_API_URL) {
console.log(`Using SERVER_API_URL: ${process.env.SERVER_API_URL}`);
return process.env.SERVER_API_URL;
}
// For server components, we normally would use environment variables
// But we need to be careful with how they're accessed
// Try to get the API URL from environment variables
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
// Check if we're running in a container/production environment
const inContainer = process.env.NODE_ENV === 'production';
// We need to get the host from somewhere to construct the URL
// In production, we can rely on the VERCEL_URL or similar
if (process.env.VERCEL_URL) {
return `https://${process.env.VERCEL_URL}/api`;
}
// If we have a configured API URL, use that
if (apiUrl) {
// If it's already an absolute URL, use it
if (apiUrl.startsWith('http')) {
return apiUrl;
}
// For container environments, use the internal port
const port = process.env.INTERNAL_API_PORT || '3000';
const protocol = (process.env.USE_HTTPS === 'false') ? 'http' : 'https';
// Otherwise, it's likely a relative path like /api
// Use localhost with the correct port for container environments
return `${protocol}://localhost:${port}${apiUrl.startsWith('/') ? apiUrl : `/${apiUrl}`}`;
}
// Last resort fallback
// Use http for container environment, https for external services
const protocol = (process.env.USE_HTTPS === 'false') ? 'http' : 'https';
const port = process.env.INTERNAL_API_PORT || '3000';
return `${protocol}://localhost:${port}/api`;
}
/**
* Server-side fetch wrapper with authentication.
*/
export async function fetchServer<T = unknown>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const cookieStore = cookies();
const authToken = cookieStore.get('Authorization')?.value;
if (!authToken) redirect('/login');
try {
const baseUrl = getBaseUrl();
// Ensure endpoint doesn't start with a slash if baseUrl ends with one
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
// Ensure baseUrl ends with a slash if it doesn't already
const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
// Combine them to get a complete URL
const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
console.log(`Server fetch to: ${url}`);
const res = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authToken}`,
...options.headers,
},
cache: 'no-store',
});
if (res.status === 401) redirect('/login');
if (!res.ok) throw new Error(`Request failed: ${res.statusText}`);
return res.json();
} catch (error) {
console.error(`Server request to ${endpoint} failed:`, error);
throw error;
}
}