+server.js 1.63 KB
import { API_HOST } from '$lib/api.js';
const API_BASE = API_HOST + '/api/organismo';

export async function GET({ url }) {
  const codigo = url.searchParams.get('codigo') || '';
  const tipo = url.searchParams.get('tipo') || 'clasificador';
  const entidad = url.searchParams.get('entidad') || '';
  const gestion = url.searchParams.get('gestion') || '';

  if (!codigo) {
    return new Response(JSON.stringify({ error: 'Missing codigo' }), {
      status: 400, headers: { 'Content-Type': 'application/json' }
    });
  }

  let apiUrl;
  if (tipo === 'clasificador') {
    apiUrl = `${API_BASE}/${codigo}`;
  } else if (tipo === 'entidades-lista') {
    apiUrl = `${API_BASE}/${codigo}/entidades`;
  } else if (tipo === 'entidad' && entidad) {
    apiUrl = `${API_BASE}/${codigo}/entidades/${entidad}`;
  } else if (tipo === 'entidades-año' && gestion) {
    apiUrl = `${API_BASE}/${codigo}/entidades?gestion=${gestion}`;
  } else {
    return new Response(JSON.stringify({ error: 'Invalid tipo' }), {
      status: 400, headers: { 'Content-Type': 'application/json' }
    });
  }

  try {
    const response = await fetch(apiUrl);
    if (!response.ok) {
      return new Response(JSON.stringify({ error: `API error: ${response.status}` }), {
        status: response.status, headers: { 'Content-Type': 'application/json' }
      });
    }
    const data = await response.json();
    return new Response(JSON.stringify(data), {
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (err) {
    return new Response(JSON.stringify({ error: 'Failed to fetch' }), {
      status: 500, headers: { 'Content-Type': 'application/json' }
    });
  }
}