81 lines
2.5 KiB
TypeScript
81 lines
2.5 KiB
TypeScript
import pg from 'pg';
|
|
import type { Aviso } from './types';
|
|
import { fixtureAvisos } from './fixtures';
|
|
|
|
const { Pool } = pg;
|
|
|
|
/**
|
|
* Trae todos los avisos ambientales (es_ambiental = true) de las dos tablas
|
|
* y los unifica en un solo array, ordenado por fecha descendente.
|
|
*
|
|
* Se ejecuta UNA vez, en build-time (frontmatter de Astro), no en cada
|
|
* visita. Si no hay DATABASE_URL configurada (p. ej. mientras se maqueta el
|
|
* frontend sin acceso al servidor privado de Hetzner), cae a datos de
|
|
* ejemplo con la misma forma, para poder trabajar en local.
|
|
*/
|
|
export async function getAvisosAmbientales(): Promise<Aviso[]> {
|
|
const connectionString = process.env.DATABASE_URL;
|
|
|
|
if (!connectionString) {
|
|
console.warn(
|
|
'[db] DATABASE_URL no definida — usando datos de ejemplo (fixtures). ' +
|
|
'Define DATABASE_URL para construir con datos reales.'
|
|
);
|
|
return fixtureAvisos;
|
|
}
|
|
|
|
const pool = new Pool({ connectionString, max: 2 });
|
|
|
|
try {
|
|
const [boib, prensa] = await Promise.all([
|
|
pool.query(`
|
|
select id, boib_fecha as fecha, organismo as fuente, titulo,
|
|
resumen, temas, url_html as url, numero_edicte
|
|
from boib_entradas
|
|
where es_ambiental = true
|
|
order by boib_fecha desc
|
|
`),
|
|
pool.query(`
|
|
select id, coalesce(fecha_publicacion, fecha_ingesta) as fecha,
|
|
fuente, titulo, resumen_ia as resumen, temas, url,
|
|
case when municipio = 'Ibiza' then 'Eivissa' else municipio end as municipio
|
|
from noticias_prensa
|
|
where es_ambiental = true
|
|
order by coalesce(fecha_publicacion, fecha_ingesta) desc
|
|
`),
|
|
]);
|
|
|
|
const avisosBoib: Aviso[] = boib.rows.map((r) => ({
|
|
id: r.id,
|
|
origen: 'boib',
|
|
titulo: r.titulo,
|
|
resumen: r.resumen ?? '',
|
|
temas: r.temas ?? [],
|
|
fuente: r.fuente ?? 'BOIB',
|
|
municipio: null, // el BOIB no trae municipio estructurado, no forzar
|
|
url: r.url,
|
|
fecha: new Date(r.fecha).toISOString(),
|
|
numeroEdicte: r.numero_edicte,
|
|
}));
|
|
|
|
const avisosPrensa: Aviso[] = prensa.rows.map((r) => ({
|
|
id: r.id,
|
|
origen: 'prensa',
|
|
titulo: r.titulo,
|
|
resumen: r.resumen ?? '',
|
|
temas: r.temas ?? [],
|
|
fuente: r.fuente,
|
|
municipio: r.municipio ?? null,
|
|
url: r.url,
|
|
fecha: new Date(r.fecha).toISOString(),
|
|
numeroEdicte: null,
|
|
}));
|
|
|
|
return [...avisosBoib, ...avisosPrensa].sort(
|
|
(a, b) => new Date(b.fecha).getTime() - new Date(a.fecha).getTime()
|
|
);
|
|
} finally {
|
|
await pool.end();
|
|
}
|
|
}
|