require('dotenv').config(); const express = require('express'); const { Pool } = require('pg'); const bodyParser = require('body-parser'); const cors = require('cors'); const path = require('path'); const app = express(); const port = process.env.PORT || 3000; app.use(cors()); app.use(bodyParser.json()); // Serve static files from the root directory app.use(express.static(path.join(__dirname, './'))); const pool = new Pool({ host: process.env.DB_HOST, port: process.env.DB_PORT, database: process.env.DB_NAME, user: process.env.DB_USER, password: process.env.DB_PASSWORD }); // Test DB Connection pool.connect() .then(() => console.log('Connected to PostgreSQL successfully')) .catch(err => console.error('Connection error', err.stack)); // API to save turbines app.post('/api/wea', async (req, res) => { const { projekt_id, turbines } = req.body; console.log(`Empfange Speicheranfrage für Projekt: ${projekt_id}, Anzahl WEAs: ${turbines?.length}`); if (!turbines || !Array.isArray(turbines)) { return res.status(400).json({ error: 'Keine validen Turbinen-Daten empfangen' }); } const client = await pool.connect(); try { await client.query('BEGIN'); console.log(`Lösche alte Einträge für Projekt ${projekt_id}...`); await client.query('DELETE FROM geodaten.wea_standorte WHERE projekt_id = $1', [projekt_id]); for(let t of turbines) { console.log(`Speichere WEA ${t.nr} (${t.type}) an Position ${t.latlng.lat}, ${t.latlng.lng}`); await client.query( `INSERT INTO geodaten.wea_standorte ( wea_nummer, hersteller, anlagentyp, nabenhoehe, rotordurchmesser, ksf_drehung, projekt_id, geom ) VALUES ($1, $2, $3, $4, $5, $6, $7, ST_SetSRID(ST_MakePoint($8, $9), 4326))`, [ t.nr, t.hersteller || '', t.type, parseInt(t.hh), parseInt(t.rd), parseInt(t.ksfAngle || 0), projekt_id, t.latlng.lng, t.latlng.lat ] ); } await client.query('COMMIT'); console.log('Speichervorgang erfolgreich abgeschlossen.'); res.status(200).json({ message: 'Windenergieanlagen erfolgreich in Datenbank gespeichert' }); } catch (e) { await client.query('ROLLBACK'); console.error('Fehler beim Speichern in die Datenbank:', e); res.status(500).json({ error: e.message }); } finally { client.release(); } }); // API to load turbines app.get('/api/wea/:projekt_id', async (req, res) => { const { projekt_id } = req.params; try { const result = await pool.query( `SELECT wea_nummer as nr, anlagentyp as type, nabenhoehe as hh, rotordurchmesser as rd, ksf_drehung as ksfAngle, ST_X(geom) as lng, ST_Y(geom) as lat FROM geodaten.wea_standorte WHERE projekt_id = $1`, [projekt_id] ); res.status(200).json(result.rows); } catch (e) { console.error('Error loading turbines', e); res.status(500).json({ error: e.message }); } }); // Catch-all route to serve index.html for any other request (optional, good for SPAs) app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'index.html')); }); app.listen(port, '0.0.0.0', () => { console.log(`Server running at http://0.0.0.0:${port}`); });