Update server.js
This commit is contained in:
31
server.js
31
server.js
@@ -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,7 +45,8 @@ console.log('------------------------------');
|
|||||||
|
|
||||||
let pool;
|
let pool;
|
||||||
|
|
||||||
const initDB = async () => {
|
const initDB = async (retries = 5) => {
|
||||||
|
while (retries > 0) {
|
||||||
try {
|
try {
|
||||||
if (!dbConfig.host || !dbConfig.user || !dbConfig.database) {
|
if (!dbConfig.host || !dbConfig.user || !dbConfig.database) {
|
||||||
throw new Error("Missing required database environment variables.");
|
throw new Error("Missing required database environment variables.");
|
||||||
@@ -74,7 +73,6 @@ const initDB = async () => {
|
|||||||
`);
|
`);
|
||||||
} 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,
|
||||||
@@ -93,10 +91,17 @@ const initDB = async () => {
|
|||||||
`);
|
`);
|
||||||
}
|
}
|
||||||
console.log(`Connected to ${DB_TYPE} database successfully.`);
|
console.log(`Connected to ${DB_TYPE} database successfully.`);
|
||||||
|
return;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Database connection/init failed:', 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);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
initDB();
|
initDB();
|
||||||
@@ -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 });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user