Search code examples
javascriptnode.jspostgresqlexpresspool

Reusing postgresql pool in other node javascript files


I am creating nodejs backend app with postgresql database. What I want is when once I create connection to database in my db.js file, that I can reuse it in other files to execute queries.

This is my db.js file

const pool = new Pool({
    user: 'us',
    host: 'localhost',
    database: 'db',
    password: 'pass',
    port: 5432,
})
pool.on('connect', () => {
    console.log('connected to the Database');
});
module.exports = () => { return pool; }

And this is how I tried to use it in index.js file

const db = require('./db.js')

app.get('/', (request, response) => {

    db().query('SELECT * FROM country'), (error, results) => {
        if (error) {
            response.send(error)
        }
        console.log(results)
        response.status(201).send(results)
    }
})

There aren't any errors, and when I go to this specific page, it's keep loading. Nothing in console also.

But, if I write a function in my db.js file and do something like pool.query(...), export it, and in my index.js I write app.get('/', exportedFunction), everything is working fine.

Is there any way not to write all my (like 50) queries in just one (db.js) file, because I want to organise my project a little bit?


Solution

  • To streamline your project structure entirely, if you're starting from scratch maybe try this :

    index.js

    const express = require('express');
    const app = express();
    
    const PORT = 8080;
    const bodyparser = require('body-parser');
    const baseRouter = require('../your-router');
    
    app.use(bodyparser.json());
    app.use(express.json());
    app.use('/', baseRouter);
    
    app.listen(PORT, function () {
    console.log('Server is running on PORT:', PORT);
    }); 
    

    your-router.js

    const Router = require('express');
    const router = Router();
    const getCountries = require('../handlers/get');
    
    router.get('/check-live', (req, res) => res.sendStatus(200));
    // route for getCountries
    router.get('/countries', getCountries);
    

    src/handler/get.js

    const YourService = require('./service/your-service');
    
    function getCountries(request, response) {
        const yourService = new YourService();
        yourService.getCountries(request)
            .then((res) => { response.send(res); })
            .catch((error) => { response.status(400).send({ message: error.message }) })
    }
    
    module.exports = getCountries;
    

    src/service/your-service.js

    const connectionPool = require('../util/dbConnect');
    class yourService {
    
        getCountries(req) {
            return new Promise(((resolve, reject) => {
                connectionPool.connect((err, db) => {
                    if (err) reject(err);
                    let query = format('SELECT * FROM country'); // get inputs from req
                    db.query(query, (err, result) => {
                        if (err) reject(err);
                        resolve(result);
                    })
                });
            }));
        }
    }
    
    module.exports = yourService;
    

    dbConnect.js

    const pgCon = require('pg')
    const PGUSER = 'USER'
    const PGDATABASE = 'localhost'
    let config = {
        user: PGUSER,
        database: PGDATABASE,
        max: 10,
        idleTimeoutMillis: 30000
    }
    
    let connectionPool = new pgCon.Pool(config);
    
    module.exports = connectionPool;
    

    Please consider this as a basic example, refactor your code to use callbacks/async awaits (in the above example you can just use callbacks not needed to convert into promise), if needed - you can have DB-layer calls from the service layer in order to extract DB methods from the service layer.