Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

pg-using-bluebird

Package Overview
Dependencies
Maintainers
3
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pg-using-bluebird - npm Package Compare versions

Comparing version 3.1.0 to 3.2.0

CHANGELOG.md

114

index.js

@@ -10,6 +10,9 @@ "use strict"; // eslint-disable-line semi

var DEFAULTS = {
var POOL_DEFAULTS = {
max: 20, // pool size
ssl: false
}
var QUERY_DEFAULTS = {
statementTimeout: '0', // the node-postgres default is no timeout
poolSize : 20,
ssl: false,
queryValuesKey: 'values',

@@ -23,51 +26,54 @@ queryTextKey: 'text'

BPromise.promisifyAll(pg)
var connectAsyncWithMultiArgs = BPromise.promisify(pg.connect, { context: pg, multiArgs: true })
function getConnection(env) {
var close
return connectAsyncWithMultiArgs(env.dbUrl).spread(function (client, done) {
close = done
return client.queryAsync("SET statement_timeout TO '" + env.statementTimeout + "'")
.then(function () { return withQueryRowsAsync(env, client) })
}).disposer(function() {
try {
if (close) close()
} catch(e) {} // eslint-disable-line no-empty
})
function getConnection(env, connector) {
var releaseConnection
return connector()
.spread(function (client, done) {
releaseConnection = done
return client.queryAsync("SET statement_timeout TO '" + env.statementTimeout + "'")
.then(function () { return decorateWithQueryRowsAsync(env, client) })
})
.disposer(function () {
releaseConnectionToPool(releaseConnection)
})
}
function getTransaction(env, tablesToLock_) {
function getTransaction(env, connector, tablesToLock_) {
var tablesToLock = tablesToLock_ || []
var close
return connectAsyncWithMultiArgs(env.dbUrl).spread(function(client, done) {
close = done
return client.queryAsync("SET statement_timeout TO '" + env.statementTimeout + "'")
.then(function () { return client.queryAsync(constructLockingBeginStatement(tablesToLock))})
.then(function () { return withQueryRowsAsync(env, client) })
}).disposer(function(tx, promise) {
if (promise.isFulfilled()) {
return tx.queryAsync('COMMIT').then(doClose)
} else {
return tx.queryAsync('ROLLBACK').then(doClose)
}
function doClose() {
try {
if (close) close()
} catch (e) { // eslint-disable-line no-empty
var releaseConnection
return connector()
.spread(function (client, done) {
releaseConnection = done
return client.queryAsync("SET statement_timeout TO '" + env.statementTimeout + "'")
.then(function () { return client.queryAsync(constructLockingBeginStatement(tablesToLock)) })
.then(function () { return decorateWithQueryRowsAsync(env, client) })
})
.disposer(function (tx, promise) {
if (promise.isFulfilled()) {
return tx.queryAsync('COMMIT').tap(function () { return releaseConnectionToPool(releaseConnection) })
} else {
return tx.queryAsync('ROLLBACK').tap(function () { return releaseConnectionToPool(releaseConnection) })
}
}
})
})
}
function withQueryRowsAsync(env, client) {
function releaseConnectionToPool(release) {
try {
if (release) release()
} catch (e) { // eslint-disable-line no-empty
}
}
function decorateWithQueryRowsAsync(env, client) {
return Object.assign(client, {
queryRowsAsync: (query, args) => queryAsync(env, client, query, args).then(getRows)
queryRowsAsync: (query, args) => queryWithCtxAsync(env, client, query, args).then(getRows)
})
}
function queryRowsAsync(env, query, args) {
var argsArray = args || []
return using(getConnection(env), function (connection) {
return queryAsync(env, connection, query, argsArray)
}).then(getRows)
function executeQueryRowsAsync(env, connector, query, args) {
return using(getConnection(env, connector), function (connection) {
return connection.queryRowsAsync(query, args)
})
}

@@ -79,3 +85,3 @@

function queryAsync(env, client, query, args) {
function queryWithCtxAsync(env, client, query, args) {
if (_.isObject(query) && query[env.queryValuesKey] && Array.isArray(args) && args.length > 0) {

@@ -173,6 +179,14 @@ throw new Error('Both query.values and args were passed to query. Please use only one of them.')

module.exports = function (env) {
var envWithDefaults = _.assign({}, DEFAULTS, env)
pg.defaults.poolSize = envWithDefaults.poolSize
pg.defaults.ssl = envWithDefaults.ssl
var poolConfig = _.assign({}, POOL_DEFAULTS, env)
// backwards compatibility
poolConfig.connectionString = env.dbUrl
poolConfig.max = env.poolSize
var pool = new pg.Pool(poolConfig)
var connectMultiArgAsync = BPromise.promisify(pool.connect, { context: pool, multiArgs: true})
var queryConfig = _.assign({}, QUERY_DEFAULTS, env)
return {

@@ -189,15 +203,15 @@ getConnection: getConnectionWithEnv,

function getConnectionWithEnv() { return getConnection(envWithDefaults) }
function getConnectionWithEnv() { return getConnection(queryConfig, connectMultiArgAsync) }
function getTransactionWithEnv(tablesToLock) { return getTransaction(envWithDefaults, tablesToLock) }
function getTransactionWithEnv(tablesToLock) { return getTransaction(queryConfig, connectMultiArgAsync, tablesToLock) }
function queryRowsWithEnv(query, args) { return queryRowsAsync(envWithDefaults, query, args)}
function queryRowsWithEnv(query, args) { return executeQueryRowsAsync(queryConfig, connectMultiArgAsync, query, args)}
function on(event, fn) {
pg.on(event, fn)
pool.on(event, fn)
}
function end() {
pg.end()
return pool.end()
}
}
{
"name": "pg-using-bluebird",
"version": "3.1.0",
"version": "3.2.0",
"description": "Helpers for managing PostgreSQL connections",

@@ -10,3 +10,6 @@ "main": "index.js",

"scripts": {
"test": "./node_modules/.bin/grunt"
"lint": "eslint ./ --ext js",
"jenkins-lint": "eslint . -f checkstyle -o eslint3.xml",
"jenkins-test": "NODE_ENV=test BLUEBIRD_DEBUG=1 JUNIT_REPORT_PATH=test-report.xml mocha --reporter mocha-jenkins-reporter --exit 'test/**/*.js'",
"test": "NODE_ENV=test BLUEBIRD_DEBUG=1 nyc --reporter text mocha --exit 'test/**/*.js'"
},

@@ -20,13 +23,12 @@ "repository": {

"lodash": "^4.17.2",
"pg": "^6.4.2",
"pg": "^7.4.3",
"string-template": "^1.0.0"
},
"devDependencies": {
"chai": "^4.1.1",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"grunt": "^1.0.1",
"grunt-cli": "^1.2.0",
"grunt-eslint": "^20.0.0",
"grunt-mocha-test": "^0.13.2",
"mocha": "^4.1.0"
"eslint": "^5.4.0",
"mocha": "^5.2.0",
"mocha-jenkins-reporter": "^0.4.0",
"nyc": "^12.0.2"
},

@@ -33,0 +35,0 @@ "license": "MIT",

@@ -8,2 +8,7 @@ # pg-using-bluebird

Why use pg-using-bluebird instead of just using node-postgres directly?
pg-using-bluebird provides a convenient interface with Bluebird promises and
resource cleanup with the using syntax, making DB querying in app code very concise
and easy to read.
This project is based on the postgres example in [Bluebird's documentation](https://github.com/petkaantonov/bluebird/blob/master/API.md#resource-management).

@@ -18,3 +23,3 @@

```javascript
var Promise = require('bluebird'),
const Promise = require('bluebird'),
pgUsingBluebird = require('pg-using-bluebird'),

@@ -24,7 +29,7 @@ db = pgUsingBluebird({dbUrl: "postgres://localhost/pgrm-tests"}),

using(db.getConnection(), function (connection) {
return connection.queryAsync("select 1").then(function (res) {
using(db.getConnection(), connection =>
connection.queryAsync("select 1").then(res => {
console.log(res.rows)
})
}).finally(function() {
).finally(() => {
db.end()

@@ -34,10 +39,16 @@ })

See [connection-test.js](test/connection-test.js) for more complete examples.
See [connection-test.js](test/connection-test.js) for more complete examples. Note
that Bluebird's using will handle cleanup of a connection and db.end() needs to be
called only when closing the entire pool.
# Documentation
# API Documentation
Requiring this module returns a function takes a single parameter
object with at least the URL to the DB (```{dbUrl: "myUrl"}```) and
returns an object with the following functions:
object with at least the URL to the DB (```{dbUrl: "myUrl"}```) and initializes a
connection pool with 20 connections. Parameters are passed directly to node-postgres,
refer to [node-postgres documentation](https://node-postgres.com/api/pool) for
configuration options.
The initializer returns an object with the following functions:
```getConnection()``` returns a DB connection

@@ -55,2 +66,12 @@

```on(event, fn)``` attach and event handler fn to the pool event event, see node-postgres documentation for event types
```end()``` shut down the connection pool, returns a promise
Both connection and transaction objects have the methods ```queryAsync(query, [args])```
for executing a query and returning the result object and ```queryRowsAsync(query, [args])```
for executing a query and returning the resulting rows. The query can be a string
or a query object, refer to node-postgres' documentation for the various options
for query objects.
# Alternatives

@@ -57,0 +78,0 @@

"use strict"; // eslint-disable-line semi
var pgrm = require('../index.js')(),
var configs = {dbUrl: "postgres://localhost/pgrm-tests"}
var pgrm = require('../index.js')(configs),
chai = require('chai'),

@@ -5,0 +6,0 @@ _ = require('lodash')

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc