Files
plantillas-proyectos/frontend/src/routes/api-sveltekit/classes/[id]/+server.ts

87 lines
2.0 KiB
TypeScript

import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ cookies, url, params }) => {
const token = cookies.get('access_token');
const { id } = params;
// Obtener company_id de la cookie o query params
const companyId = cookies.get('active_company_id') || url.searchParams.get('company_id');
if (!companyId) {
return new Response(
JSON.stringify({ error: 'No company selected' }),
{
status: 400,
headers: {
'Content-Type': 'application/json'
}
}
);
}
// Configurar la URL de la API usando las variables de entorno
let apiUrl = process.env.INTERNAL_API_URL;
if (!apiUrl) {
apiUrl = process.env.VITE_API_URL;
// Reemplazar 'localhost' con 'backend' para llamadas desde el servidor (SSR)
apiUrl = apiUrl?.replace('localhost', 'backend').replace('127.0.0.1', 'backend');
}
// Normalizar la URL
const baseUrl = apiUrl?.endsWith('/') ? apiUrl : `${apiUrl}/`;
try {
const fetchUrl = `${baseUrl}v1/a76/classes/${id}?company_id=${companyId}`;
const response = await fetch(
fetchUrl,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
}
);
if (!response.ok) {
const errorText = await response.text();
console.error('Error response from backend:', errorText);
return new Response(
JSON.stringify({
error: 'Failed to fetch class',
details: errorText
}),
{
status: response.status,
headers: {
'Content-Type': 'application/json'
}
}
);
}
const data = await response.json();
return new Response(JSON.stringify(data), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
} catch (error) {
console.error('Error in class API route:', error);
return new Response(
JSON.stringify({
error: 'Internal server error',
message: error instanceof Error ? error.message : 'Unknown error'
}),
{
status: 500,
headers: {
'Content-Type': 'application/json'
}
}
);
}
};