trello_fake/lib/dolibarrClient.ts

96 lines
2.7 KiB
TypeScript
Raw Normal View History

2026-01-28 10:44:49 +00:00
/**
* 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
2026-01-28 10:44:49 +00:00
*/
// 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)');
}
2026-05-27 19:17:58 +00:00
const [baseEndpoint, queryString] = endpoint.split('?');
let url = `${apiUrl}/${baseEndpoint}?DOLAPIKEY=${apiKey}`;
if (queryString) {
url += `&${queryString}`;
}
const res = await fetch(url, {
...options,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
...options.headers,
},
// Sin cache en servidor para evitar datos antiguos
cache: 'no-store'
});
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 = {}) {
2026-01-28 10:44:49 +00:00
const url = `/api/dolibarr/${endpoint}`;
2026-01-28 10:44:49 +00:00
const res = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
...options.headers,
},
});
if (!res.ok) {
2026-01-28 10:44:49 +00:00
const errorData = await res.json().catch(() => ({ error: 'Unknown error' }));
console.error("Error en la llamada Dolibarr (proxy):", res.status, errorData);
2026-01-28 10:44:49 +00:00
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);
}