85 lines
No EOL
2.3 KiB
JavaScript
85 lines
No EOL
2.3 KiB
JavaScript
import express from 'express';
|
|
import cors from 'cors';
|
|
import mysql from 'mysql2/promise';
|
|
import dotenv from 'dotenv';
|
|
|
|
dotenv.config();
|
|
|
|
const app = express();
|
|
app.use(cors());
|
|
app.use(express.json());
|
|
|
|
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);
|
|
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' });
|
|
}
|
|
});
|
|
|
|
const PORT = process.env.PORT || 3000;
|
|
app.listen(PORT, () => {
|
|
console.log(`Server running on port ${PORT}`);
|
|
}); |