Skip to content

Latest commit

 

History

History
90 lines (71 loc) · 2.17 KB

README.md

File metadata and controls

90 lines (71 loc) · 2.17 KB

Buybrain postgres

This is a ergonomic wrapper around the pg module for interacting with Postgres databases and testing code that interacts with databases.

  • Promise based interface (with bluebird)
  • More flexible argument handling with pg-format rather than using prepared statements.
  • Automatically releases client resources to prevent leakage
  • Convenient transactions
  • Includes scriptable mock version of database client

Getting started

Install by running

npm install --save buybrain-pg

Import with

const db = require('buybrain-pg');

Examples

buybrain-pg relies on Bluebird resource management and the using() function. For convenience, it is re-exported in the buybrain-pg module.

Create a new pool

const pool = db.newPool({
    user: 'test',
    password: 'test',
    database: 'test',
    host: 'localhost'
});

Run a query and output the result

db.using(pool.connect(), client => client.query('SELECT 1'))
    .then(res => {
        console.log(res);
    });

Run multiple queries in a transaction

db.using(pool.connect(), client => {
    return client.transactional(() => {
        return client.query('INSERT INTO test SELECT 1')
            .then(() => client.query("INSERT INTO test SELECT 2"));
    });
});

Running tests

The tests are run against a real Postgres instance. An easy way to get this up and running with the correct credentials and database is by using Docker. After installing it, just run

docker run --rm -p 5433:5432 -e POSTGRES_DB=test -e POSTGRES_USER=test -e POSTGRES_PASSWORD=test postgres

Tests are written for nodeunit. Make sure nodeunit is installed by running

npm install -g nodeunit

Then, from the project root, run

nodeunit

Using the mock version for testing

The mock client is tested itself in this unit test, which is a great example of how it can be used for your own tests.

License

MIT