Update server.js
This commit is contained in:
119
server.js
119
server.js
@@ -1,3 +1,4 @@
|
||||
|
||||
import express from 'express';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
@@ -18,13 +19,11 @@ app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(express.static(path.join(__dirname, 'dist')));
|
||||
|
||||
// --- 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';
|
||||
|
||||
@@ -36,7 +35,6 @@ const dbConfig = {
|
||||
port: process.env.DB_PORT || (DB_TYPE === 'postgres' ? 5432 : 3306),
|
||||
};
|
||||
|
||||
// Debug Log
|
||||
console.log('--- Database Configuration ---');
|
||||
console.log(`Type: ${DB_TYPE}`);
|
||||
console.log(`Host: ${dbConfig.host}`);
|
||||
@@ -47,55 +45,62 @@ console.log('------------------------------');
|
||||
|
||||
let pool;
|
||||
|
||||
const initDB = async () => {
|
||||
try {
|
||||
if (!dbConfig.host || !dbConfig.user || !dbConfig.database) {
|
||||
throw new Error("Missing required database environment variables.");
|
||||
}
|
||||
const initDB = async (retries = 5) => {
|
||||
while (retries > 0) {
|
||||
try {
|
||||
if (!dbConfig.host || !dbConfig.user || !dbConfig.database) {
|
||||
throw new Error("Missing required database environment variables.");
|
||||
}
|
||||
|
||||
if (DB_TYPE === 'postgres') {
|
||||
const { Pool } = pg;
|
||||
pool = new Pool(dbConfig);
|
||||
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 TEXT,
|
||||
body_html TEXT,
|
||||
footer_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,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
if (DB_TYPE === 'postgres') {
|
||||
const { Pool } = pg;
|
||||
pool = new Pool(dbConfig);
|
||||
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 TEXT,
|
||||
body_html TEXT,
|
||||
footer_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);
|
||||
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,
|
||||
created_at TIMESTAMP DEFAULT 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);
|
||||
} catch (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) => {
|
||||
console.log("POST /api/templates - Ricevuta richiesta di salvataggio");
|
||||
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 body = t.body || '';
|
||||
const footer = t.footer || '';
|
||||
@@ -154,6 +166,7 @@ app.post('/api/templates', async (req, res) => {
|
||||
];
|
||||
|
||||
try {
|
||||
console.log(`Tentativo di salvataggio nel DB (${DB_TYPE}) per chiave: ${templateKey}`);
|
||||
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)
|
||||
@@ -188,10 +201,10 @@ app.post('/api/templates', async (req, res) => {
|
||||
`;
|
||||
await pool.query(query, params);
|
||||
}
|
||||
console.log(`Template saved: ${t.name} (${t.id})`);
|
||||
console.log("Salvataggio DB riuscito");
|
||||
res.json({ success: true });
|
||||
} 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 });
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user