Advertisement
Guest User

Postgres Connection from Node

a guest
Apr 13th, 2025
38
0
298 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express');
  2. const fs = require('fs');
  3. const { faker } = require('@faker-js/faker');
  4. const { Pool } = require('pg');
  5. const { DefaultAzureCredential} = require('@azure/identity');
  6.  
  7. const app = express();
  8. const port = process.env.PORT || 3000;
  9.  
  10. const pg_host = process.env.PG_HOST;
  11. const pg_port = process.env.PG_PORT;
  12. const pg_db = process.env.PG_DB;
  13. const pg_user = process.env.PG_USER;
  14.  
  15. let dbPool = null;
  16.  
  17. // Function to create a new pool
  18. async function createDbPool() {
  19.   try {
  20.     const credential = new DefaultAzureCredential();
  21.     const tokenResponse = await credential.getToken("https://ossrdbms-aad.database.windows.net/.default");
  22.     console.log(tokenResponse.token);
  23.  
  24.     const pool = new Pool({
  25.       host: pg_host,
  26.       port: pg_port,
  27.       database: pg_db,
  28.       user: pg_user,
  29.       password: tokenResponse.token,
  30.       ssl: {
  31.         rejectUnauthorized: false,
  32.         ca: fs.readFileSync("./certs/DigiCertGlobalRootCA.crt").toString()
  33.       },
  34.       max: 30,
  35.       idleTimeoutMillis: 30000,
  36.       connectionTimeoutMillis: 20000
  37.     });
  38.  
  39.     console.log('New DB pool created');
  40.     console.log('Pool status:');
  41.     console.log('Total clients:', pool.totalCount);    // All clients (idle + checked out)
  42.     console.log('Idle clients:', pool.idleCount);      // Currently idle clients
  43.     console.log('Waiting clients:', pool.waitingCount); // Clients waiting for a connection
  44.     return pool;
  45.   } catch (err) {
  46.     console.error('Failed to create DB pool:', err);
  47.     return null;
  48.   }
  49. }
  50.  
  51. // Middleware to attach the current pool to each request
  52. app.use((req, res, next) => {
  53.   if (!dbPool) {
  54.     return res.status(500).send('Database pool is not available');
  55.   }
  56.   req.db = dbPool;
  57.   next();
  58. });
  59.  
  60. // Renew the pool every 60 seconds
  61. async function schedulePoolRenewal() {
  62.   setInterval(async () => {
  63.     console.log('Renewing DB pool...');
  64.     const newPool = await createDbPool();
  65.     if (newPool) {
  66.       const oldPool = dbPool;
  67.       dbPool = newPool;
  68.  
  69.       // Clean up old pool
  70.       if (oldPool) {
  71.         setTimeout(() => {
  72.           oldPool.end().then(() => console.log('Old pool closed'));
  73.         }, 5000); // delay to avoid interrupting active queries
  74.       }
  75.     }
  76.   }, 60000);
  77. }
  78.  
  79. app.get('/', async (req, res) => {
  80.   try {
  81.     const result = await req.db.query('SELECT NOW()');
  82.     res.send(`DB time: ${result.rows[0].now}`);
  83.   } catch (err) {
  84.     console.error('Error querying the database:', err);
  85.     res.status(500).send('Error fetching data from the database');
  86.   }
  87. });
  88.  
  89. // Initialize app
  90. (async () => {
  91.   dbPool = await createDbPool();
  92.   if (!dbPool) {
  93.     console.error('Failed to initialize DB pool. Exiting.');
  94.     process.exit(1);
  95.   }
  96.  
  97.   schedulePoolRenewal();
  98.  
  99.   app.listen(port, '0.0.0.0', () => {
  100.     console.log(`App listening on port ${port}`);
  101.   });
  102. })();
  103.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement