Update server.js
This commit is contained in:
164
server.js
164
server.js
@@ -2,7 +2,6 @@ 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';
|
||||||
|
|
||||||
@@ -18,22 +17,20 @@ 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
|
// DB Configuration for internal MySQL
|
||||||
// Normalize DB_TYPE: allow 'postgres', 'postgresql', 'Postgres', etc.
|
|
||||||
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,
|
host: process.env.DB_HOST || 'localhost',
|
||||||
user: process.env.DB_USER,
|
user: process.env.DB_USER || 'root',
|
||||||
password: process.env.DB_PASSWORD,
|
password: process.env.DB_PASSWORD || 'password',
|
||||||
database: process.env.DB_NAME,
|
database: process.env.DB_NAME || 'email_templates',
|
||||||
port: process.env.DB_PORT || (DB_TYPE === 'postgres' ? 5432 : 3306),
|
port: process.env.DB_PORT || 3306,
|
||||||
|
waitForConnections: true,
|
||||||
|
connectionLimit: 10,
|
||||||
|
queueLimit: 0
|
||||||
};
|
};
|
||||||
|
|
||||||
// Debug Log: Print config to console (masking password)
|
// Debug Log: Print config to console (masking password)
|
||||||
console.log('--- Database Configuration ---');
|
console.log('--- Database Configuration ---');
|
||||||
console.log(`Type: ${DB_TYPE} (Input: ${process.env.DB_TYPE || 'default'})`);
|
|
||||||
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}`);
|
||||||
@@ -46,57 +43,34 @@ let pool;
|
|||||||
// Initialize DB Connection
|
// Initialize DB Connection
|
||||||
const initDB = async () => {
|
const initDB = async () => {
|
||||||
try {
|
try {
|
||||||
if (!dbConfig.host || !dbConfig.user || !dbConfig.database) {
|
pool = mysql.createPool(dbConfig);
|
||||||
throw new Error("Missing required database environment variables (DB_HOST, DB_USER, or DB_NAME).");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (DB_TYPE === 'postgres') {
|
// Test connection
|
||||||
const { Pool } = pg;
|
const connection = await pool.getConnection();
|
||||||
pool = new Pool(dbConfig);
|
console.log('Connected to MySQL database successfully.');
|
||||||
|
connection.release();
|
||||||
|
|
||||||
// Create table for Postgres
|
// Create table for MySQL
|
||||||
// Using JSONB for variables
|
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 JSON,
|
||||||
required_variables JSONB,
|
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
|
);
|
||||||
);
|
`);
|
||||||
`);
|
|
||||||
} else {
|
|
||||||
// MySQL
|
|
||||||
pool = mysql.createPool(dbConfig);
|
|
||||||
|
|
||||||
// Create table for MySQL
|
console.log('Email templates table ready.');
|
||||||
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 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.`);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Database connection failed:', err);
|
console.error('Database initialization failed:', err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -104,18 +78,10 @@ const initDB = async () => {
|
|||||||
initDB();
|
initDB();
|
||||||
|
|
||||||
// API Routes
|
// API Routes
|
||||||
|
|
||||||
// GET All Templates
|
// GET All Templates
|
||||||
app.get('/api/templates', async (req, res) => {
|
app.get('/api/templates', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
let rows;
|
const [rows] = await pool.query('SELECT * FROM email_templates ORDER BY updated_at DESC');
|
||||||
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
|
// Map DB fields back to frontend types
|
||||||
const templates = rows.map(row => ({
|
const templates = rows.map(row => ({
|
||||||
@@ -140,7 +106,8 @@ app.get('/api/templates', async (req, res) => {
|
|||||||
// SAVE (Upsert) Template
|
// 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 in Postgres
|
|
||||||
|
// 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 || '';
|
||||||
@@ -162,42 +129,23 @@ app.post('/api/templates', async (req, res) => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (DB_TYPE === 'postgres') {
|
const query = `
|
||||||
// Postgres requires explicit casting for JSONB parameters when passed as strings ($10::jsonb)
|
INSERT INTO email_templates (id, template_key, name, description, subject, header_html, body_html, footer_html, full_html, required_variables, updated_at)
|
||||||
const query = `
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
|
||||||
INSERT INTO email_templates (id, template_key, name, description, subject, header_html, body_html, footer_html, full_html, required_variables, updated_at)
|
ON DUPLICATE KEY UPDATE
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, NOW())
|
template_key = VALUES(template_key),
|
||||||
ON CONFLICT (id) DO UPDATE SET
|
name = VALUES(name),
|
||||||
template_key = EXCLUDED.template_key,
|
description = VALUES(description),
|
||||||
name = EXCLUDED.name,
|
subject = VALUES(subject),
|
||||||
description = EXCLUDED.description,
|
header_html = VALUES(header_html),
|
||||||
subject = EXCLUDED.subject,
|
body_html = VALUES(body_html),
|
||||||
header_html = EXCLUDED.header_html,
|
footer_html = VALUES(footer_html),
|
||||||
body_html = EXCLUDED.body_html,
|
full_html = VALUES(full_html),
|
||||||
footer_html = EXCLUDED.footer_html,
|
required_variables = VALUES(required_variables),
|
||||||
full_html = EXCLUDED.full_html,
|
updated_at = NOW();
|
||||||
required_variables = EXCLUDED.required_variables,
|
`;
|
||||||
updated_at = NOW();
|
|
||||||
`;
|
await pool.query(query, params);
|
||||||
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, updated_at)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
|
|
||||||
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),
|
|
||||||
updated_at = NOW();
|
|
||||||
`;
|
|
||||||
await pool.query(query, params);
|
|
||||||
}
|
|
||||||
res.json({ success: true });
|
res.json({ success: true });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Save Template Error:", err);
|
console.error("Save Template Error:", err);
|
||||||
@@ -209,11 +157,7 @@ app.post('/api/templates', async (req, res) => {
|
|||||||
// DELETE Template
|
// 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 = ?', [req.params.id]);
|
||||||
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 });
|
res.json({ success: true });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|||||||
Reference in New Issue
Block a user