Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node - Postgres driver setup with node-postgres

I am trying to integrate node-postgres driver and learn to do a simple CRUD operations. In my app.js, I do something like this:

...
var postgres = require('./adapters/postgres')
var postClient = new postgres(conf);
...
postClient.connect(function (dbconn) {
    app.dbconn = dbconn;
    app.conf = conf;

    console.log("************************************************************");
    console.log(new Date() + ' | CRUD Server Listening on ' + conf['web']['port']);
    console.log("************************************************************");

    server.listen(conf['web']['port']);

    var Routes = require('./routes/http-routes');
    new Routes(app);
});

Inside my adapters/postgres.js file, I have the following content:

const Client = require('pg');
const postClient = new Client(conf)({
    host: conf['postgres'].host,
    port: conf['postgres'].port,
    dbname: conf['postgres'].dbname,
    username: conf['postgres'].username,
    password: conf['postgres'].password,
    dbconn: null,
});
module.exports = postClient;
postClient.prototype.connect = function (cbk) {
    var self = this;
    client.connect(function (err, db) {
        console.log(new Date() + " | Postgres Server Connection Establised...");
        console.log(new Date() + " | Current database: ", db.databaseName);
        if (!err) {
            console.log(new Date() + " | Postgres Server Authenticated...");
            self.dbconn = db;
            cbk(db);
        } else {
            console.log(new Date() + " | Postgres Server Error in connection...");
            console.log(err);
            self.dbconn = db;
            cbk(db);
        }
    });
};

With the above code, I keep getting this error: ReferenceError: conf is not defined so I added it as var conf = require('../config/conf');. This is not a proper solution since I would like to pass it from the app.js. Next, even with this added I get the following error: TypeError: Client is not a constructor. Can someone guide on fixing both these errors?

like image 838
JackSlayer94 Avatar asked Oct 30 '22 01:10

JackSlayer94


1 Answers

Export a factory function that takes the configuration object and returns an instance of the client. Client isn't a default export in pg so it needs to be destructured.

const { Client } = require('pg');

const createPgClient = (conf) => {
    const pgClient = new Client(conf)({
        host: conf['postgres'].host,
        port: conf['postgres'].port,
        dbname: conf['postgres'].dbname,
        username: conf['postgres'].username,
        password: conf['postgres'].password,
        dbconn: null,
    });

    pgClient.prototype.connect = function (callback) {

        client.connect()
        .then(() => {
            console.log(new Date() + " | Postgres Server Authenticated...");
        })
        .catch((err) => {
            console.log(new Date() + " | Postgres Server Error in connection...");
            console.log(err);
        })
        .finally(()=> {
            self.dbconn = this;
            callback(this);
        });

    };
    return pgClient;
};
module.exports = createPgClient;

Use this factory function in your app.js to create a client.

const createPgClient = require('./adapters/postgres')
cont pgClient = createPgClient(conf);

pg.connect(function (dbconn) {
    app.dbconn = dbconn;
    app.conf = conf;

    console.log("************************************************************");
    console.log(new Date() + ' | CRUD Server Listening on ' + conf['web']['port']);
    console.log("************************************************************");

    server.listen(conf['web']['port']);

    const Routes = require('./routes/http-routes');
    new Routes(app);
});
like image 74
Oluwafemi Sule Avatar answered Nov 15 '22 06:11

Oluwafemi Sule