113 lines
3.8 KiB
JavaScript
Executable file
113 lines
3.8 KiB
JavaScript
Executable file
// FLUJOS_APP.js ubicado en /var/www/flujos/FLUJOS/BACK_BACK/
|
|
|
|
require('dotenv').config(); // Cargar variables de entorno desde .env
|
|
|
|
const express = require('express');
|
|
const path = require('path');
|
|
const bodyParser = require('body-parser');
|
|
const helmet = require('helmet');
|
|
const { MongoClient } = require('mongodb');
|
|
|
|
const app = express();
|
|
const port = process.env.PORT || 3000;
|
|
|
|
// Configurar Helmet con CSP personalizado
|
|
app.use(
|
|
helmet.contentSecurityPolicy({
|
|
directives: {
|
|
defaultSrc: ["'self'"],
|
|
scriptSrc: [
|
|
"'self'",
|
|
"'unsafe-inline'",
|
|
'https://unpkg.com',
|
|
'https://cdnjs.cloudflare.com',
|
|
'https://fonts.googleapis.com',
|
|
'https://fonts.gstatic.com',
|
|
],
|
|
styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
|
|
imgSrc: ["'self'", 'data:'],
|
|
connectSrc: ["'self'", 'ws://localhost:3000'],
|
|
fontSrc: ["'self'", 'https://fonts.gstatic.com'],
|
|
},
|
|
})
|
|
);
|
|
|
|
app.use(bodyParser.json());
|
|
|
|
// Configurar el directorio de archivos estáticos
|
|
app.use(express.static(path.join(__dirname, '../VISUALIZACION/public')));
|
|
|
|
// Ruta para la página principal
|
|
app.get('/', (req, res) => {
|
|
res.sendFile(path.join(__dirname, '../VISUALIZACION/public/climate.html'));
|
|
});
|
|
|
|
// Conexión a MongoDB usando variables de entorno
|
|
const mongoUrl = process.env.MONGO_URL || 'mongodb://localhost:27017';
|
|
const dbName = process.env.DB_NAME || 'FLUJOS_DATOS';
|
|
const mongoClient = new MongoClient(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
|
|
|
|
// Endpoint para obtener datos de climate
|
|
app.get('/api/climate-data', async (req, res) => {
|
|
try {
|
|
// Conectar a MongoDB
|
|
await mongoClient.connect();
|
|
const db = mongoClient.db(dbName);
|
|
|
|
// Acceder a las colecciones necesarias
|
|
const noticiasCollection = db.collection('noticias');
|
|
const comparacionesCollection = db.collection('comparaciones');
|
|
|
|
// Obtener los parámetros de consulta del cliente (si los hay)
|
|
const { subtematica, palabraClave, fechaInicio, fechaFin } = req.query;
|
|
|
|
// Construir la consulta para obtener los nodos (noticias)
|
|
const nodesQuery = { tema: 'cambio climático' };
|
|
if (subtematica) nodesQuery.subtema = subtematica;
|
|
if (palabraClave) nodesQuery.contenido = { $regex: palabraClave, $options: 'i' };
|
|
if (fechaInicio && fechaFin) {
|
|
nodesQuery.fecha = {
|
|
$gte: new Date(fechaInicio),
|
|
$lte: new Date(fechaFin)
|
|
};
|
|
}
|
|
|
|
// Ejecutar la consulta y obtener los resultados
|
|
const nodesCursor = noticiasCollection.find(nodesQuery).limit(50); // Puedes ajustar el límite según tus necesidades
|
|
const nodes = await nodesCursor.toArray();
|
|
|
|
// Construir la consulta para obtener los enlaces (comparaciones)
|
|
const linksQuery = { porcentaje_similitud: { $gte: 5 } }; // Ajusta el valor según necesites
|
|
const linksCursor = comparacionesCollection.find(linksQuery);
|
|
const links = await linksCursor.toArray();
|
|
|
|
// Formatear los datos para enviarlos al cliente
|
|
const formattedNodes = nodes.map(result => ({
|
|
id: result.archivo,
|
|
group: result.tipo,
|
|
tema: result.tema,
|
|
content: result.contenido,
|
|
fecha: result.fecha,
|
|
}));
|
|
|
|
const formattedLinks = links.map(result => ({
|
|
source: result.noticia1,
|
|
target: result.noticia2,
|
|
value: result.porcentaje_similitud,
|
|
}));
|
|
|
|
// Enviar los datos al cliente en formato JSON
|
|
res.json({ nodes: formattedNodes, links: formattedLinks });
|
|
} catch (error) {
|
|
console.error('Error al obtener datos:', error);
|
|
res.status(500).json({ error: 'Error al obtener datos' });
|
|
} finally {
|
|
// Cerrar la conexión a la base de datos
|
|
await mongoClient.close();
|
|
}
|
|
});
|
|
|
|
// Iniciar el servidor
|
|
app.listen(port, () => {
|
|
console.log(`La aplicación está escuchando en http://localhost:${port}`);
|
|
});
|