pg-using-bluebird
Advanced tools
Comparing version 3.1.0 to 3.2.0
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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
6
76
35554
11
601
+ Addedbuffer-writer@2.0.0(transitive)
+ Addedpacket-reader@1.0.0(transitive)
+ Addedpg@7.18.2(transitive)
+ Addedpg-packet-stream@1.1.0(transitive)
+ Addedpg-pool@2.0.10(transitive)
+ Addedpg-types@2.2.0(transitive)
+ Addedpostgres-array@2.0.0(transitive)
- Removedbuffer-writer@1.0.1(transitive)
- Removedgeneric-pool@2.4.3(transitive)
- Removedjs-string-escape@1.0.1(transitive)
- Removedobject-assign@4.1.0(transitive)
- Removedpacket-reader@0.3.1(transitive)
- Removedpg@6.4.2(transitive)
- Removedpg-pool@1.8.0(transitive)
- Removedpg-types@1.13.0(transitive)
- Removedpostgres-array@1.0.3(transitive)
Updatedpg@^7.4.3