0

What is the best way to provide 'pgp' to the following function?
Considering 'db' can be db connection, transaction (tx), or task from the above.

module.exports = async (db, tableName, records) => {
  const record_ = records[0]
  const columns_ = []
  for (const c_ in record_) { columns_.push(c_) }
  const insert_ = pgp.helpers.insert(records, columns_, tableName)
  return db.result(insert_, null, r => r.rowCount)
}
Le Ma
  • 3
  • 5

1 Answers1

0

See Where should I initialize pg-promise, which shows you:

module.exports = {
    pgp, db
};

...so you can import it and use whenever you need.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • a) 'pgp' initialized inside package_1 - according to your description within specific module. Than package_2 uses package_1. On the top package_main uses package_1 and package_2. As a result I'm getting valid pgp within package_main, but undefined within package_2. Can you please advise how it can be resolved? – Le Ma Feb 28 '19 at 20:48
  • I have no idea what package 2 or main package are. The database module has no other dependencies, so if you are running into some dependency loop, that's on your side, and unrelated here. – vitaly-t Feb 28 '19 at 20:56
  • And again - this is not very convenient. Sorry to get back!.. According to your approach I need to pass 'pgp' to many functions that are dialing with data. Because it is needed to call 'helpers.insert', 'QueryFile' and others... Alternative way to obtain 'db.$config.pgp' is hugely helpful but it is valid only for db. I highly need the same reference from TX and TASK ! Why it's missing? – Le Ma Mar 01 '19 at 16:55
  • @LeonidMaksimshin Why won't you just return `{db, helpers, QueryFile}` from your database module? That's how modulated namespaces are normally used. – vitaly-t Mar 01 '19 at 17:03
  • Such approach works but let me ask: What the reason of db.$config ? Simplification I guess ? Is it good practice to have many small routines for data manipulation that have connection in form of db/tx/task - depending on it's place withing program logic ? So why all three form of connection don't have similar interface to $config ? After all most set of data manipulation functions are the same... – Le Ma Mar 01 '19 at 19:32
  • @LeMa [The API](http://vitaly-t.github.io/pg-promise/Database.html#$config) explains why it is there - `to help integrating type Database directly with third-party libraries.` That's why it does not exist within task/tx context. It was not deemed needed, since within the same app anything can be simply exported, while during integration, only the `db` object is typically available. – vitaly-t Mar 01 '19 at 20:23