77 lines
1.8 KiB
JavaScript
77 lines
1.8 KiB
JavaScript
const mysql = require('mysql2/promise');
|
|
const { Client } = 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) {
|
|
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
|
|
});
|
|
|
|
// Test the connection
|
|
const connection = await pool.getConnection();
|
|
console.log('[Database] Connected successfully through SSH tunnel');
|
|
connection.release();
|
|
|
|
return pool;
|
|
} catch (error) {
|
|
console.error('[Database] Error initializing pool:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function getConnection() {
|
|
if (!pool) {
|
|
throw new Error('Database pool not initialized');
|
|
}
|
|
return pool.getConnection();
|
|
}
|
|
|
|
module.exports = {
|
|
initPool,
|
|
getConnection,
|
|
getPool: () => pool
|
|
};
|