Files
EmailManager/server.js
2025-12-23 12:19:41 +01:00

213 lines
6.7 KiB
JavaScript

import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import mysql from 'mysql2/promise';
import pg from 'pg';
import cors from 'cors';
import dotenv from 'dotenv';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3000;
// 1. CORS deve essere la prima cosa per gestire le richieste OPTIONS dei browser
app.use(cors());
app.options('*', cors());
// 2. Logging immediato di ogni richiesta
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} - Status: ${res.statusCode} (${duration}ms)`);
});
next();
});
// 3. Parser JSON con limite aumentato (fondamentale per template HTML grandi)
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
// 4. File statici
app.use(express.static(path.join(__dirname, 'dist')));
const rawDbType = (process.env.DB_TYPE || 'mysql').toLowerCase().trim();
const DB_TYPE = (rawDbType === 'postgres' || rawDbType === 'postgresql') ? 'postgres' : 'mysql';
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT || (DB_TYPE === 'postgres' ? 5432 : 3306),
};
console.log('--- App Version: 1.0.2 ---');
console.log(`DB Type: ${DB_TYPE}`);
console.log(`DB Host: ${dbConfig.host}`);
let pool;
const initDB = async (retries = 5) => {
while (retries > 0) {
try {
if (!dbConfig.host || !dbConfig.user || !dbConfig.database) {
throw new Error("Missing required database environment variables (DB_HOST, DB_USER, DB_NAME).");
}
if (DB_TYPE === 'postgres') {
const { Pool } = pg;
pool = new Pool(dbConfig);
await pool.query('SELECT 1'); // Test connection
} else {
pool = mysql.createPool(dbConfig);
await pool.query('SELECT 1'); // Test connection
}
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("FATAL: Could not connect to database.");
// Non usciamo per permettere al server di servire i file statici e mostrare errori via API
} else {
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
}
};
initDB();
app.get('/api/templates', async (req, res) => {
try {
if (!pool) return res.status(503).json({ error: "Database not connected" });
let rows;
if (DB_TYPE === 'postgres') {
const result = await pool.query('SELECT * FROM email_templates ORDER BY updated_at DESC');
rows = result.rows;
} else {
const [result] = await pool.query('SELECT * FROM email_templates ORDER BY updated_at DESC');
rows = result;
}
const templates = rows.map(row => ({
id: row.id,
name: row.name,
description: row.description,
subject: row.subject,
header: row.header_html,
body: row.body_html,
footer: row.footer_html,
variables: typeof row.required_variables === 'string' ? JSON.parse(row.required_variables) : (row.required_variables || []),
updatedAt: row.updated_at
}));
res.json(templates);
} catch (err) {
console.error("Fetch Error:", err);
res.status(500).json({ error: 'Failed to fetch templates', details: err.message });
}
});
app.post('/api/templates', async (req, res) => {
const t = req.body;
if (!t.name || !t.id) {
return res.status(400).json({ error: "Name and ID are required" });
}
const header = t.header || '';
const body = t.body || '';
const footer = t.footer || '';
const fullHtml = `${header}${body}${footer}`;
const templateKey = (t.name || '').trim().toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '');
const variablesJson = JSON.stringify(t.variables || []);
const params = [
t.id,
templateKey,
t.name,
t.description || '',
t.subject || '',
header,
body,
footer,
fullHtml,
variablesJson
];
try {
if (!pool) throw new Error("Database not connected");
if (DB_TYPE === 'postgres') {
const query = `
INSERT INTO email_templates (id, template_key, name, description, subject, header_html, body_html, footer_html, full_html, required_variables, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, NOW())
ON CONFLICT (id) DO UPDATE SET
template_key = EXCLUDED.template_key,
name = EXCLUDED.name,
description = EXCLUDED.description,
subject = EXCLUDED.subject,
header_html = EXCLUDED.header_html,
body_html = EXCLUDED.body_html,
footer_html = EXCLUDED.footer_html,
full_html = EXCLUDED.full_html,
required_variables = EXCLUDED.required_variables,
updated_at = NOW();
`;
await pool.query(query, params);
} else {
const query = `
INSERT INTO email_templates (id, template_key, name, description, subject, header_html, body_html, footer_html, full_html, required_variables)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
template_key = VALUES(template_key),
name = VALUES(name),
description = VALUES(description),
subject = VALUES(subject),
header_html = VALUES(header_html),
body_html = VALUES(body_html),
footer_html = VALUES(footer_html),
full_html = VALUES(full_html),
required_variables = VALUES(required_variables);
`;
await pool.query(query, params);
}
res.json({ success: true });
} catch (err) {
console.error("DB Save Error:", err.message);
res.status(500).json({ error: 'Database save failed', details: err.message });
}
});
app.delete('/api/templates/:id', async (req, res) => {
try {
if (!pool) return res.status(503).json({ error: "Database not connected" });
if (DB_TYPE === 'postgres') {
await pool.query('DELETE FROM email_templates WHERE id = $1', [req.params.id]);
} else {
await pool.query('DELETE FROM email_templates WHERE id = ?', [req.params.id]);
}
res.json({ success: true });
} catch (err) {
console.error("Delete Error:", err);
res.status(500).json({ error: 'Failed to delete template' });
}
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on port ${PORT}`);
});