Update server.js

This commit is contained in:
fcarraUniSa
2025-12-23 12:00:48 +01:00
committed by GitHub
parent 4e5226d213
commit 95b9a0f820

119
server.js
View File

@@ -1,3 +1,4 @@
import express from 'express'; import express from 'express';
import path from 'path'; import path from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
@@ -18,13 +19,11 @@ app.use(cors());
app.use(express.json()); app.use(express.json());
app.use(express.static(path.join(__dirname, 'dist'))); app.use(express.static(path.join(__dirname, 'dist')));
// --- LOGGING MIDDLEWARE ---
app.use((req, res, next) => { app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`); console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); next();
}); });
// DB Configuration
const rawDbType = (process.env.DB_TYPE || 'mysql').toLowerCase().trim(); const rawDbType = (process.env.DB_TYPE || 'mysql').toLowerCase().trim();
const DB_TYPE = (rawDbType === 'postgres' || rawDbType === 'postgresql') ? 'postgres' : 'mysql'; const DB_TYPE = (rawDbType === 'postgres' || rawDbType === 'postgresql') ? 'postgres' : 'mysql';
@@ -36,7 +35,6 @@ const dbConfig = {
port: process.env.DB_PORT || (DB_TYPE === 'postgres' ? 5432 : 3306), port: process.env.DB_PORT || (DB_TYPE === 'postgres' ? 5432 : 3306),
}; };
// Debug Log
console.log('--- Database Configuration ---'); console.log('--- Database Configuration ---');
console.log(`Type: ${DB_TYPE}`); console.log(`Type: ${DB_TYPE}`);
console.log(`Host: ${dbConfig.host}`); console.log(`Host: ${dbConfig.host}`);
@@ -47,55 +45,62 @@ console.log('------------------------------');
let pool; let pool;
const initDB = async () => { const initDB = async (retries = 5) => {
try { while (retries > 0) {
if (!dbConfig.host || !dbConfig.user || !dbConfig.database) { try {
throw new Error("Missing required database environment variables."); if (!dbConfig.host || !dbConfig.user || !dbConfig.database) {
} throw new Error("Missing required database environment variables.");
}
if (DB_TYPE === 'postgres') { if (DB_TYPE === 'postgres') {
const { Pool } = pg; const { Pool } = pg;
pool = new Pool(dbConfig); pool = new Pool(dbConfig);
await pool.query(` await pool.query(`
CREATE TABLE IF NOT EXISTS email_templates ( CREATE TABLE IF NOT EXISTS email_templates (
id VARCHAR(255) PRIMARY KEY, id VARCHAR(255) PRIMARY KEY,
template_key VARCHAR(255) UNIQUE NOT NULL, template_key VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL,
description TEXT, description TEXT,
subject VARCHAR(255), subject VARCHAR(255),
header_html TEXT, header_html TEXT,
body_html TEXT, body_html TEXT,
footer_html TEXT, footer_html TEXT,
full_html TEXT, full_html TEXT,
required_variables JSONB, required_variables JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
); );
`); `);
} else { } else {
pool = mysql.createPool(dbConfig); pool = mysql.createPool(dbConfig);
// Use MEDIUMTEXT for MySQL to handle larger emails await pool.query(`
await pool.query(` CREATE TABLE IF NOT EXISTS email_templates (
CREATE TABLE IF NOT EXISTS email_templates ( id VARCHAR(255) PRIMARY KEY,
id VARCHAR(255) PRIMARY KEY, template_key VARCHAR(255) UNIQUE NOT NULL,
template_key VARCHAR(255) UNIQUE NOT NULL, name VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL, description TEXT,
description TEXT, subject VARCHAR(255),
subject VARCHAR(255), header_html MEDIUMTEXT,
header_html MEDIUMTEXT, body_html MEDIUMTEXT,
body_html MEDIUMTEXT, footer_html MEDIUMTEXT,
footer_html MEDIUMTEXT, full_html MEDIUMTEXT,
full_html MEDIUMTEXT, required_variables JSON,
required_variables JSON, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP );
); `);
`); }
console.log(`Connected to ${DB_TYPE} database successfully.`);
return;
} catch (err) {
retries -= 1;
console.error(`Database connection failed (${retries} retries left):`, err.message);
if (retries === 0) {
console.error("No more retries. Exiting.");
process.exit(1);
}
await new Promise(resolve => setTimeout(resolve, 5000));
} }
console.log(`Connected to ${DB_TYPE} database successfully.`);
} catch (err) {
console.error('Database connection/init failed:', err);
process.exit(1);
} }
}; };
@@ -127,12 +132,19 @@ app.get('/api/templates', async (req, res) => {
res.json(templates); res.json(templates);
} catch (err) { } catch (err) {
console.error("Fetch Error:", err); console.error("Fetch Error:", err);
res.status(500).json({ error: 'Failed to fetch templates' }); res.status(500).json({ error: 'Failed to fetch templates', details: err.message });
} }
}); });
app.post('/api/templates', async (req, res) => { app.post('/api/templates', async (req, res) => {
console.log("POST /api/templates - Ricevuta richiesta di salvataggio");
const t = req.body; const t = req.body;
if (!t.name || !t.id) {
console.error("ERRORE: Dati mancanti nella richiesta POST", t);
return res.status(400).json({ error: "Nome e ID sono obbligatori" });
}
const header = t.header || ''; const header = t.header || '';
const body = t.body || ''; const body = t.body || '';
const footer = t.footer || ''; const footer = t.footer || '';
@@ -154,6 +166,7 @@ app.post('/api/templates', async (req, res) => {
]; ];
try { try {
console.log(`Tentativo di salvataggio nel DB (${DB_TYPE}) per chiave: ${templateKey}`);
if (DB_TYPE === 'postgres') { if (DB_TYPE === 'postgres') {
const query = ` const query = `
INSERT INTO email_templates (id, template_key, name, description, subject, header_html, body_html, footer_html, full_html, required_variables, updated_at) INSERT INTO email_templates (id, template_key, name, description, subject, header_html, body_html, footer_html, full_html, required_variables, updated_at)
@@ -188,10 +201,10 @@ app.post('/api/templates', async (req, res) => {
`; `;
await pool.query(query, params); await pool.query(query, params);
} }
console.log(`Template saved: ${t.name} (${t.id})`); console.log("Salvataggio DB riuscito");
res.json({ success: true }); res.json({ success: true });
} catch (err) { } catch (err) {
console.error("SAVE ERROR:", err.message); console.error("ERRORE SALVATAGGIO DB:", err.message);
res.status(500).json({ error: 'Failed to save template', details: err.message }); res.status(500).json({ error: 'Failed to save template', details: err.message });
} }
}); });