question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Consider using `Promise.using` syntax for transactions

See original GitHub issue

From your example, doing this:

var Promise = require(‘bluebird’);

knex.transaction(function(t) {

  knex('books')
    .transacting(t)
    .insert({name: 'Old Books'})
    .then(function(row) {

      return Promise.all(_.map([
        {title: 'Canterbury Tales'},
        {title: 'Moby Dick'},
        {title: 'Hamlet'}
      ], function(info) {

        info.row_id = row.id;

        // Some validation could take place here.
        return knex('book').transacting(t).insert(info);

      }));
    })
    .then(t.commit, t.rollback);

}).then(function() {
  console.log('3 new books saved.');
}, function() {
  console.log('Error saving the books.');
});

var Promise = require(‘bluebird’);

Can become this:

knex.transaction(function(t) {
  return knex('books')
    .transacting(t)
    .insert({name: 'Old Books'})
    .then(function(row) {
       return Promise.all(_.map([
         {title: 'Canterbury Tales'},
         {title: 'Moby Dick'},
         {title: 'Hamlet'}
        ], function(info) {
        info.row_id = row.id;
        // Some validation could take place here.
        return knex('book').transacting(t).insert(info);
      }));
    });
}).then(function() { // this happens if the above promise resolved.
  console.log('3 new books saved.');
}, function() { // this happens if the promise returned from the transaction rejected
  console.log('Error saving the books.');
});

See https://github.com/petkaantonov/bluebird/blob/iterators/API.md#resource-management

Even the transacting(t) part could be removed here, you can also use .bind to set the this value to the transaction.

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:27 (13 by maintainers)

github_iconTop GitHub Comments

1reaction
paynecodescommented, Dec 11, 2014

I’ve been surfing the net for some good information on how to write mocha tests that will rollback changes in each test when the test completes. I can see from some of the examples above and from #263 how this might be done when using knex directly in tests.

I’m wondering, though, if anyone can offer up a best practice for rolling back changes to the database when doing other types of tests such as http request tests. Assume there aren’t always appropriate http methods available on a resource to delete/rollback, and this should be handled automatically/transparently by the test runner.

A few considerations:

  1. Figure out a way to use begin and rollback mentioned here.
  2. Call bookshelf.knex.raw('truncate table ' + tableName + ' cascade'); before each test, and stand up some test related seed data once this completes.
  3. EDIT Use a Template Database to CREATE and new db after DROPing the temporary test database.

Any other thoughts or suggestions?

1reaction
andrewvccommented, May 7, 2014

I’d like to add that I think this makes a ton of sense. Especially the ‘bind’ part. I’m currently working on a ‘begin; rollback’ database cleaning strategy for my tests (I’m using postgres, where this is sane), which means I have to wrap all the queries and transactions in a single test in a larger transaction, then roll it back. It’s a fast and foolproof way of cleaning up between tests.

The current syntax makes this unduly hard!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Pg-promise : transaction issue - Stack Overflow
I got something strange with pg-promise with a transaction with generators. This is what I want : Get or register a user (getOrRegisterUser);...
Read more >
Using promises - JavaScript - MDN Web Docs
A Promise is an object representing the eventual completion or failure of an asynchronous operation. Since most people are consumers of already- ...
Read more >
How to retrieve transaction hash value from the Promise ...
You need to await your promise. Your code should read: await returnPromise = web3.eth.accounts.signTransaction(tx, privateKey).then(signed ...
Read more >
Promise - Dexie.js
Syntax. return new Dexie.Promise(function (resolve, reject) { // Do something ... Promise to interact with native promises in order to maintain transaction ......
Read more >
Transactions and promises in Node.js - Medium
We have a database which need to be consistently updated with some batch of data and Node.JS application which executes queries in database....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found