/** * Cliente para la API de Dolibarr * * - En el CLIENTE: usa la API Route de Next.js (/api/dolibarr) para mantener la API key segura * - En el SERVIDOR: llama directamente a Dolibarr con las credenciales del entorno */ // Detectar si estamos en el servidor o cliente const isServer = typeof window === 'undefined'; /** * Fetch directo a Dolibarr (usado en el servidor) */ async function dolibarrDirectFetch(endpoint: string, options: RequestInit = {}) { const apiUrl = process.env.DOLIBARR_API_URL || process.env.NEXT_PUBLIC_API_URL; const apiKey = process.env.DOLIBARR_API_KEY || process.env.NEXT_PUBLIC_DOLIBARR_API_KEY; if (!apiUrl || !apiKey) { throw new Error('Dolibarr configuration missing (DOLIBARR_API_URL or DOLIBARR_API_KEY)'); } const url = `${apiUrl}/${endpoint}?DOLAPIKEY=${apiKey}`; const res = await fetch(url, { ...options, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', ...options.headers, }, // Cache durante 60 segundos en servidor next: { revalidate: 60 } }); if (!res.ok) { const errorText = await res.text(); console.error("Error en la llamada directa a Dolibarr:", res.status, errorText); throw new Error(`Dolibarr API error: ${res.status}`); } return res.json(); } /** * Fetch via API Route (usado en el cliente) */ async function dolibarrProxyFetch(endpoint: string, options: RequestInit = {}) { const url = `/api/dolibarr/${endpoint}`; const res = await fetch(url, { ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); if (!res.ok) { const errorData = await res.json().catch(() => ({ error: 'Unknown error' })); console.error("Error en la llamada Dolibarr (proxy):", res.status, errorData); throw new Error(errorData.error || "Dolibarr API error"); } return res.json(); } /** * Cliente principal de Dolibarr * Automáticamente detecta el entorno y usa el método apropiado */ export async function dolibarrFetch(endpoint: string, options: RequestInit = {}) { if (isServer) { return dolibarrDirectFetch(endpoint, options); } else { return dolibarrProxyFetch(endpoint, options); } } /** * Forzar fetch directo (útil para Server Components) */ export async function dolibarrServerFetch(endpoint: string, options: RequestInit = {}) { return dolibarrDirectFetch(endpoint, options); } /** * Forzar fetch via proxy (útil para Client Components) */ export async function dolibarrClientFetch(endpoint: string, options: RequestInit = {}) { return dolibarrProxyFetch(endpoint, options); }