pg-transact

1.0.1 • Public • Published

pg-transact

Build Status

A nicer API on node-postgres transactions

Usage

var pg = require('pg.js');
var pgTransact = require('pg-transact');
 
function transaction(client, cb){
  // everything in here is run as a transaction
  client.query('SELECT NOW() as when', function(err, result){
    if(err){
      // passing an error to the callback does a rollback on the transaction
      return cb(err);
    }
 
    // passing a `null` error and a result will resolve the transaction as the result
    cb(null, result);
  });
}
 
pg.connect(connectionString, function(err, client, done){
  if(err){
    throw err;
  }
 
  pgTransact(client, transaction, done)
    .then(console.log, console.error);
});

It also will work with a returned promise:

var pg = require('pg.js');
var pgTransact = require('pg-transact');
 
function transaction(client, cb){
  return new Promise(function(resolve, reject){
    client.query('SELECT NOW() as when', function(err, result){
      if(err){
        return reject(err);
      }
 
      resolve(result);
    });
  });
}
 
pg.connect(connectionString, function(err, client, done){
  if(err){
    throw err;
  }
 
  pgTransact(client, transaction, done)
    .then(console.log, console.error);
});

/pg-transact/

    Package Sidebar

    Install

    npm i pg-transact

    Weekly Downloads

    0

    Version

    1.0.1

    License

    MIT

    Last publish

    Collaborators

    • monteslu