enable ssl for pg connection

This commit is contained in:
2026-05-04 11:02:48 +02:00
parent 8cfeb1ed49
commit 33aadc8c1d
+36 -46
View File
@@ -15,10 +15,9 @@ app.use(express.json({ limit: '10mb' }));
// PostgreSQL connection pool // PostgreSQL connection pool
function handleHeaders(headers) { function handleHeaders(headers) {
const alias = (headers['db-alias'] || 'default').toUpperCase().replace(/-/g, '_'); const alias = (headers['db-alias'] || 'default').toUpperCase().replace(/-/g, '_');
let pool={ let pool = {
host: process.env[`DB_${alias}_HOST`], host: process.env[`DB_${alias}_HOST`],
port: process.env[`DB_${alias}_PORT`], port: process.env[`DB_${alias}_PORT`],
database: process.env[`DB_${alias}_DATABASE`], database: process.env[`DB_${alias}_DATABASE`],
@@ -29,33 +28,31 @@ function handleHeaders(headers) {
connectionTimeoutMillis: 2000, connectionTimeoutMillis: 2000,
}; };
const allUndefined = pool.host=== undefined && pool.port=== undefined && pool.database=== undefined && pool.user=== undefined && pool.password=== undefined; const allUndefined =
const someUndefined = pool.host=== '' || pool.port=== '' || pool.database=== '' || pool.user=== '' || pool.password=== ''; pool.host === undefined && pool.port === undefined && pool.database === undefined && pool.user === undefined && pool.password === undefined;
const someUndefined = pool.host === '' || pool.port === '' || pool.database === '' || pool.user === '' || pool.password === '';
const someDefined = pool.host != undefined || pool.port != undefined || pool.database != undefined || pool.user != undefined || pool.password != undefined; const someDefined = pool.host != undefined || pool.port != undefined || pool.database != undefined || pool.user != undefined || pool.password != undefined;
if (allUndefined) { if (allUndefined) {
throw new Error('Invalid db alias'); throw new Error('Invalid db alias');
} } else if (someUndefined && someDefined) {
else if(someUndefined && someDefined) {
console.log(pool); console.log(pool);
if(pool.host === '') { if (pool.host === '') {
throw new Error('Host is not configured for the specified db alias'); throw new Error('Host is not configured for the specified db alias');
} }
if(pool.port === '') { if (pool.port === '') {
throw new Error('Port is not configured for the specified db alias'); throw new Error('Port is not configured for the specified db alias');
} }
if(pool.database === '') { if (pool.database === '') {
throw new Error('Database is not configured for the specified db alias'); throw new Error('Database is not configured for the specified db alias');
} }
if(pool.user === '') { if (pool.user === '') {
throw new Error('User is not configured for the specified db alias'); throw new Error('User is not configured for the specified db alias');
} }
if(pool.password === '') { if (pool.password === '') {
throw new Error('Password is not configured for the specified db alias'); throw new Error('Password is not configured for the specified db alias');
} }
} else {
}
else{
return new Pool({ return new Pool({
host: process.env[`DB_${alias}_HOST`], host: process.env[`DB_${alias}_HOST`],
port: process.env[`DB_${alias}_PORT`], port: process.env[`DB_${alias}_PORT`],
@@ -65,10 +62,9 @@ function handleHeaders(headers) {
max: 20, max: 20,
idleTimeoutMillis: 30000, idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000, connectionTimeoutMillis: 2000,
ssl: { rejectUnauthorized: false },
}); });
} }
} }
// Health check endpoint // Health check endpoint
@@ -76,7 +72,7 @@ app.get('/api/health', (req, res) => {
res.json({ res.json({
status: 'ok', status: 'ok',
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
node_version: process.version node_version: process.version,
}); });
}); });
@@ -87,7 +83,7 @@ app.post('/api/postgres/select', async (req, res) => {
if (!query) { if (!query) {
return res.status(422).json({ return res.status(422).json({
success: false, success: false,
error: 'Query is required' error: 'Query is required',
}); });
} }
@@ -99,13 +95,13 @@ app.post('/api/postgres/select', async (req, res) => {
res.json({ res.json({
success: true, success: true,
data: result.rows, data: result.rows,
count: result.rowCount count: result.rowCount,
}); });
} catch (error) { } catch (error) {
console.error('SELECT Error:', error); console.error('SELECT Error:', error);
res.status(400).json({ res.status(400).json({
success: false, success: false,
error: error.message error: error.message,
}); });
} finally { } finally {
if (pool) await pool.end(); if (pool) await pool.end();
@@ -119,7 +115,7 @@ app.post('/api/postgres/execute', async (req, res) => {
if (!query) { if (!query) {
return res.status(422).json({ return res.status(422).json({
success: false, success: false,
error: 'Query is required' error: 'Query is required',
}); });
} }
@@ -130,13 +126,13 @@ app.post('/api/postgres/execute', async (req, res) => {
res.json({ res.json({
success: true, success: true,
affected_rows: result.rowCount affected_rows: result.rowCount,
}); });
} catch (error) { } catch (error) {
console.error('EXECUTE Error:', error); console.error('EXECUTE Error:', error);
res.status(400).json({ res.status(400).json({
success: false, success: false,
error: error.message error: error.message,
}); });
} finally { } finally {
if (pool) await pool.end(); if (pool) await pool.end();
@@ -150,7 +146,7 @@ app.post('/api/postgres/transaction', async (req, res) => {
if (!queries || !Array.isArray(queries)) { if (!queries || !Array.isArray(queries)) {
return res.status(422).json({ return res.status(422).json({
success: false, success: false,
error: 'Queries array is required' error: 'Queries array is required',
}); });
} }
@@ -167,7 +163,7 @@ app.post('/api/postgres/transaction', async (req, res) => {
const result = await client.query(item.query, item.bindings || []); const result = await client.query(item.query, item.bindings || []);
results.push({ results.push({
rowCount: result.rowCount, rowCount: result.rowCount,
success: true success: true,
}); });
} }
@@ -175,14 +171,14 @@ app.post('/api/postgres/transaction', async (req, res) => {
res.json({ res.json({
success: true, success: true,
results: results results: results,
}); });
} catch (error) { } catch (error) {
if (client) await client.query('ROLLBACK'); if (client) await client.query('ROLLBACK');
console.error('TRANSACTION Error:', error); console.error('TRANSACTION Error:', error);
res.status(400).json({ res.status(400).json({
success: false, success: false,
error: error.message error: error.message,
}); });
} finally { } finally {
if (client) client.release(); if (client) client.release();
@@ -197,7 +193,7 @@ app.post('/api/postgres/insert', async (req, res) => {
if (!table || !data) { if (!table || !data) {
return res.status(422).json({ return res.status(422).json({
success: false, success: false,
error: 'Table and data are required' error: 'Table and data are required',
}); });
} }
@@ -209,7 +205,7 @@ app.post('/api/postgres/insert', async (req, res) => {
const placeholders = values.map((_, i) => `$${i + 1}`).join(', '); const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
const query = ` const query = `
INSERT INTO "${table}" (${columns.map(c => `"${c}"`).join(', ')}) INSERT INTO "${table}" (${columns.map((c) => `"${c}"`).join(', ')})
VALUES (${placeholders}) VALUES (${placeholders})
RETURNING * RETURNING *
`; `;
@@ -218,13 +214,13 @@ app.post('/api/postgres/insert', async (req, res) => {
res.json({ res.json({
success: true, success: true,
data: result.rows[0] data: result.rows[0],
}); });
} catch (error) { } catch (error) {
console.error('INSERT Error:', error); console.error('INSERT Error:', error);
res.status(400).json({ res.status(400).json({
success: false, success: false,
error: error.message error: error.message,
}); });
} finally { } finally {
if (pool) await pool.end(); if (pool) await pool.end();
@@ -238,7 +234,7 @@ app.post('/api/postgres/update', async (req, res) => {
if (!table || !data || !where) { if (!table || !data || !where) {
return res.status(422).json({ return res.status(422).json({
success: false, success: false,
error: 'Table, data and where are required' error: 'Table, data and where are required',
}); });
} }
@@ -250,13 +246,9 @@ app.post('/api/postgres/update', async (req, res) => {
const whereColumns = Object.keys(where); const whereColumns = Object.keys(where);
const whereValues = Object.values(where); const whereValues = Object.values(where);
const setClause = setColumns const setClause = setColumns.map((col, i) => `"${col}" = $${i + 1}`).join(', ');
.map((col, i) => `"${col}" = $${i + 1}`)
.join(', ');
const whereClause = whereColumns const whereClause = whereColumns.map((col, i) => `"${col}" = $${setValues.length + i + 1}`).join(' AND ');
.map((col, i) => `"${col}" = $${setValues.length + i + 1}`)
.join(' AND ');
const query = ` const query = `
UPDATE "${table}" UPDATE "${table}"
@@ -268,13 +260,13 @@ app.post('/api/postgres/update', async (req, res) => {
res.json({ res.json({
success: true, success: true,
affected_rows: result.rowCount affected_rows: result.rowCount,
}); });
} catch (error) { } catch (error) {
console.error('UPDATE Error:', error); console.error('UPDATE Error:', error);
res.status(400).json({ res.status(400).json({
success: false, success: false,
error: error.message error: error.message,
}); });
} finally { } finally {
if (pool) await pool.end(); if (pool) await pool.end();
@@ -288,7 +280,7 @@ app.post('/api/postgres/delete', async (req, res) => {
if (!table || !where) { if (!table || !where) {
return res.status(422).json({ return res.status(422).json({
success: false, success: false,
error: 'Table and where are required' error: 'Table and where are required',
}); });
} }
@@ -298,9 +290,7 @@ app.post('/api/postgres/delete', async (req, res) => {
const whereColumns = Object.keys(where); const whereColumns = Object.keys(where);
const whereValues = Object.values(where); const whereValues = Object.values(where);
const whereClause = whereColumns const whereClause = whereColumns.map((col, i) => `"${col}" = $${i + 1}`).join(' AND ');
.map((col, i) => `"${col}" = $${i + 1}`)
.join(' AND ');
const query = `DELETE FROM "${table}" WHERE ${whereClause}`; const query = `DELETE FROM "${table}" WHERE ${whereClause}`;
@@ -308,13 +298,13 @@ app.post('/api/postgres/delete', async (req, res) => {
res.json({ res.json({
success: true, success: true,
affected_rows: result.rowCount affected_rows: result.rowCount,
}); });
} catch (error) { } catch (error) {
console.error('DELETE Error:', error); console.error('DELETE Error:', error);
res.status(400).json({ res.status(400).json({
success: false, success: false,
error: error.message error: error.message,
}); });
} finally { } finally {
if (pool) await pool.end(); if (pool) await pool.end();