5

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?

3
  • @brianc any help will be appreciated! Commented Oct 9, 2017 at 12:16
  • A good example: Designing a RESTful API With Node and Postgres. Commented Oct 9, 2017 at 12:25
  • 1
    @vitaly-t Thanks, I will use that as a base! Just for understanding can you help me with the current code? Commented Oct 9, 2017 at 17:30

1 Answer 1

2
+25

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

With the code posted above, I get the following error: var pgClient = createPgClient(conf); ^ ReferenceError: createPgClient is not defined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.