Search code examples
javascriptnode.jspg-promise

How to extend pg-promise interface with function


I have a node.js module pg-promise instantiated as follows.

const pgp = require('pg-promise')();

// Database connection details;
const cn = {
    host: 'localhost', // 'localhost' is the default;
    ...
}


// Create db connection and verify it
var db = pgp(process.env.DATABASE_URL || cn);
db.one('Select version()')
    .then(data => {
        log.info('Connected: ', data);
    })
    .catch(error => {
        log.error("Error connecting to db", error);
    })

// extension methods
db.findById = function (table, id) {
    log.debug('read ', table, id);
    return db.one('Select * from ' + table + ' where id = $1', id);
}

module.exports = db;

The db object is an instance of interface type pgPromise.IDatabase<{}, pg.Iclient>

I would like to be able to call the functions provided by this lib along with my own functions.:

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

db.any('Select query..')
  .then(data => { res.send(data); })
  .catch(err => { log.error(err); });

db.findById('users',1)
  .then(data => { res.send(data); })
  .catch(err => { log.error(err); });

But when I run it I get the error

TypeError: db.findById is not a function

I tried this too but with the same effect.

module.exports = db;
module.exports.findById = function()...;

Only one sollution I could come up with was this:

module.exports = {
  db: db,
  findById: function(){
    ...
  }
}

But it is now ugly to use it other modules, as I need always to ask specificaly for the db property.


Solution

  • From the author of pg-promise.


    Database protocol in pg-promise is extendable, supporting event extend that lets you extend the protocol on all levels. You need this level of automation, because when it comes to the essential Tasks and Transactions, which encapsulate the allocated connection, the protocol becomes dynamic, and so you need a special provision to make the protocol extension work automatically, which is exactly what event extend does.

    In order to understand it better, I wrote pg-promise-demo to show how to do it correctly, plus some other high-level stuff that comes useful most of the time.