Update server.js

This commit is contained in:
fcarraUniSa
2025-12-23 10:35:04 +01:00
committed by GitHub
parent 8f01fc8a6f
commit 68f3b1d6c0

124
server.js
View File

@@ -2,6 +2,7 @@ import express from 'express';
import path from 'path'; import path from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import mysql from 'mysql2/promise'; import mysql from 'mysql2/promise';
import pg from 'pg';
import cors from 'cors'; import cors from 'cors';
import dotenv from 'dotenv'; import dotenv from 'dotenv';
@@ -17,40 +18,44 @@ 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')));
// DB Configuration for internal MySQL // --- LOGGING MIDDLEWARE ---
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
});
// DB Configuration
const rawDbType = (process.env.DB_TYPE || 'mysql').toLowerCase().trim();
const DB_TYPE = (rawDbType === 'postgres' || rawDbType === 'postgresql') ? 'postgres' : 'mysql';
const dbConfig = { const dbConfig = {
host: process.env.DB_HOST || 'localhost', host: process.env.DB_HOST,
user: process.env.DB_USER || 'root', user: process.env.DB_USER,
password: process.env.DB_PASSWORD || 'password', password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'email_templates', database: process.env.DB_NAME,
port: process.env.DB_PORT || 3306, port: process.env.DB_PORT || (DB_TYPE === 'postgres' ? 5432 : 3306),
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
}; };
// Debug Log: Print config to console (masking password) // Debug Log
console.log('--- Database Configuration ---'); console.log('--- Database Configuration ---');
console.log(`Type: ${DB_TYPE}`);
console.log(`Host: ${dbConfig.host}`); console.log(`Host: ${dbConfig.host}`);
console.log(`User: ${dbConfig.user}`); console.log(`User: ${dbConfig.user}`);
console.log(`Database: ${dbConfig.database}`); console.log(`Database: ${dbConfig.database}`);
console.log(`Port: ${dbConfig.port}`); console.log(`Port: ${dbConfig.port}`);
console.log(`Password: ${dbConfig.password ? '******' : '(Not Set)'}`);
console.log('------------------------------'); console.log('------------------------------');
let pool; let pool;
// Initialize DB Connection
const initDB = async () => { const initDB = async () => {
try { try {
pool = mysql.createPool(dbConfig); if (!dbConfig.host || !dbConfig.user || !dbConfig.database) {
throw new Error("Missing required database environment variables.");
}
// Test connection if (DB_TYPE === 'postgres') {
const connection = await pool.getConnection(); const { Pool } = pg;
console.log('Connected to MySQL database successfully.'); pool = new Pool(dbConfig);
connection.release();
// Create table for MySQL
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,
@@ -62,28 +67,51 @@ const initDB = async () => {
body_html TEXT, body_html TEXT,
footer_html TEXT, footer_html TEXT,
full_html TEXT, full_html TEXT,
required_variables JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
`);
} else {
pool = mysql.createPool(dbConfig);
// Use MEDIUMTEXT for MySQL to handle larger emails
await pool.query(`
CREATE TABLE IF NOT EXISTS email_templates (
id VARCHAR(255) PRIMARY KEY,
template_key VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(255) NOT NULL,
description TEXT,
subject VARCHAR(255),
header_html MEDIUMTEXT,
body_html MEDIUMTEXT,
footer_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('Email templates table ready.'); console.log(`Connected to ${DB_TYPE} database successfully.`);
} catch (err) { } catch (err) {
console.error('Database initialization failed:', err); console.error('Database connection/init failed:', err);
process.exit(1); process.exit(1);
} }
}; };
initDB(); initDB();
// API Routes
// GET All Templates
app.get('/api/templates', async (req, res) => { app.get('/api/templates', async (req, res) => {
try { try {
const [rows] = await pool.query('SELECT * FROM email_templates ORDER BY updated_at DESC'); 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;
}
// Map DB fields back to frontend types
const templates = rows.map(row => ({ const templates = rows.map(row => ({
id: row.id, id: row.id,
name: row.name, name: row.name,
@@ -92,22 +120,19 @@ app.get('/api/templates', async (req, res) => {
header: row.header_html, header: row.header_html,
body: row.body_html, body: row.body_html,
footer: row.footer_html, footer: row.footer_html,
variables: typeof row.required_variables === 'string' ? JSON.parse(row.required_variables) : row.required_variables, variables: typeof row.required_variables === 'string' ? JSON.parse(row.required_variables) : (row.required_variables || []),
updatedAt: row.updated_at updatedAt: row.updated_at
})); }));
res.json(templates); res.json(templates);
} catch (err) { } catch (err) {
console.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' });
} }
}); });
// SAVE (Upsert) Template
app.post('/api/templates', async (req, res) => { app.post('/api/templates', async (req, res) => {
const t = req.body; const t = req.body;
// Ensure default values to prevent undefined errors
const header = t.header || ''; const header = t.header || '';
const body = t.body || ''; const body = t.body || '';
const footer = t.footer || ''; const footer = t.footer || '';
@@ -129,9 +154,27 @@ app.post('/api/templates', async (req, res) => {
]; ];
try { try {
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)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()) 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 ON DUPLICATE KEY UPDATE
template_key = VALUES(template_key), template_key = VALUES(template_key),
name = VALUES(name), name = VALUES(name),
@@ -141,31 +184,32 @@ app.post('/api/templates', async (req, res) => {
body_html = VALUES(body_html), body_html = VALUES(body_html),
footer_html = VALUES(footer_html), footer_html = VALUES(footer_html),
full_html = VALUES(full_html), full_html = VALUES(full_html),
required_variables = VALUES(required_variables), required_variables = VALUES(required_variables);
updated_at = NOW();
`; `;
await pool.query(query, params); await pool.query(query, params);
}
console.log(`Template saved: ${t.name} (${t.id})`);
res.json({ success: true }); res.json({ success: true });
} catch (err) { } catch (err) {
console.error("Save Template Error:", err); console.error("SAVE ERROR:", err.message);
// Return specific error details to help debugging on the client
res.status(500).json({ error: 'Failed to save template', details: err.message }); res.status(500).json({ error: 'Failed to save template', details: err.message });
} }
}); });
// DELETE Template
app.delete('/api/templates/:id', async (req, res) => { app.delete('/api/templates/:id', async (req, res) => {
try { try {
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]); await pool.query('DELETE FROM email_templates WHERE id = ?', [req.params.id]);
}
res.json({ success: true }); res.json({ success: true });
} catch (err) { } catch (err) {
console.error(err); console.error("Delete Error:", err);
res.status(500).json({ error: 'Failed to delete template' }); res.status(500).json({ error: 'Failed to delete template' });
} }
}); });
// Handle React Routing
app.get('*', (req, res) => { app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html')); res.sendFile(path.join(__dirname, 'dist', 'index.html'));
}); });