Merge branch 'master' into add-product-upload-page

This commit is contained in:
2025-02-23 15:40:54 -05:00
parent 3f16413769
commit f628774267
47 changed files with 4674 additions and 3199 deletions

View File

@@ -1,65 +1,40 @@
const mysql = require('mysql2/promise');
const { Client } = require('ssh2');
const { Pool } = require('pg');
const { Client: SSHClient } = require('ssh2');
let pool;
async function setupSshTunnel() {
const sshConfig = {
host: process.env.PROD_SSH_HOST,
port: process.env.PROD_SSH_PORT || 22,
username: process.env.PROD_SSH_USER,
privateKey: process.env.PROD_SSH_KEY_PATH
? require('fs').readFileSync(process.env.PROD_SSH_KEY_PATH)
: undefined,
compress: true
};
return new Promise((resolve, reject) => {
const ssh = new Client();
ssh.on('error', (err) => {
console.error('SSH connection error:', err);
reject(err);
});
ssh.on('ready', () => {
ssh.forwardOut(
'127.0.0.1',
0,
process.env.PROD_DB_HOST || 'localhost',
process.env.PROD_DB_PORT || 3306,
(err, stream) => {
if (err) reject(err);
resolve({ ssh, stream });
}
);
}).connect(sshConfig);
});
}
async function initPool(config) {
// Log config without sensitive data
const safeConfig = {
host: config.host,
user: config.user,
database: config.database,
port: config.port,
max: config.max,
idleTimeoutMillis: config.idleTimeoutMillis,
connectionTimeoutMillis: config.connectionTimeoutMillis,
ssl: config.ssl,
password: config.password ? '[password set]' : '[no password]'
};
console.log('[Database] Initializing pool with config:', safeConfig);
try {
const tunnel = await setupSshTunnel();
pool = mysql.createPool({
...config,
stream: tunnel.stream,
host: process.env.PROD_DB_HOST || 'localhost',
user: process.env.PROD_DB_USER,
password: process.env.PROD_DB_PASSWORD,
database: process.env.PROD_DB_NAME,
port: process.env.PROD_DB_PORT || 3306
});
// Create the pool
pool = new Pool(config);
// Test the connection
const connection = await pool.getConnection();
console.log('[Database] Connected successfully through SSH tunnel');
connection.release();
const client = await pool.connect();
try {
await client.query('SELECT NOW()');
console.log('[Database] Pool connection test successful');
} finally {
client.release();
}
return pool;
} catch (error) {
console.error('[Database] Error initializing pool:', error);
throw error;
} catch (err) {
console.error('[Database] Connection failed:', err);
throw err;
}
}
@@ -67,11 +42,27 @@ async function getConnection() {
if (!pool) {
throw new Error('Database pool not initialized');
}
return pool.getConnection();
return pool.connect();
}
// Helper function to execute a query with error handling
async function query(text, params = []) {
if (!pool) {
throw new Error('Database pool not initialized');
}
try {
const result = await pool.query(text, params);
return result;
} catch (err) {
console.error('[Database] Query error:', err);
throw err;
}
}
module.exports = {
initPool,
getConnection,
getPool: () => pool
getPool: () => pool,
query
};