import express from 'express'; import cors from 'cors'; import mysql from 'mysql2/promise'; import dotenv from 'dotenv'; import path from 'path'; import { fileURLToPath } from 'url'; import { webcrypto } from 'crypto'; dotenv.config(); const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const crypto = webcrypto; const app = express(); app.use(cors()); app.use(express.json()); // Serve static files from the dist directory app.use(express.static(path.join(__dirname, '../dist'))); const pool = mysql.createPool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, waitForConnections: true, connectionLimit: 10, queueLimit: 0 }); // Test database connection pool.getConnection() .then(connection => { console.log('Database connected successfully'); connection.release(); }) .catch(error => { console.error('Error connecting to the database:', error); console.error('Connection details:', { host: process.env.DB_HOST, user: process.env.DB_USER, database: process.env.DB_NAME }); process.exit(1); }); // Get all servers app.get('/api/servers', async (req, res) => { try { const [rows] = await pool.query('SELECT * FROM servers ORDER BY created_at DESC'); const servers = rows.map(row => ({ ...row, cpus: Array(row.cpu_count).fill({ model: row.cpu_model, cores: row.cpu_cores }) })); res.json(servers); } catch (error) { console.error('Error fetching servers:', error); res.status(500).json({ error: 'Internal server error' }); } }); // Add new server app.post('/api/servers', async (req, res) => { try { const { name, model, cpus, ram_gb, proxmox_url } = req.body; const id = crypto.randomUUID(); await pool.query( 'INSERT INTO servers (id, name, model, cpu_model, cpu_cores, cpu_count, ram_gb, proxmox_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [id, name, model, cpus[0].model, cpus[0].cores, cpus.length, ram_gb, proxmox_url] ); const [newServer] = await pool.query('SELECT * FROM servers WHERE id = ?', [id]); res.status(201).json(newServer[0]); } catch (error) { console.error('Error adding server:', error); res.status(500).json({ error: 'Internal server error' }); } }); // Delete server app.delete('/api/servers/:id', async (req, res) => { try { const { id } = req.params; await pool.query('DELETE FROM servers WHERE id = ?', [id]); res.status(204).send(); } catch (error) { console.error('Error deleting server:', error); res.status(500).json({ error: 'Internal server error' }); } }); // Serve index.html for all other routes (SPA support) app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '../dist/index.html')); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });