From 5a006285269c4f5ae7398cf3ec6812054f7acd05 Mon Sep 17 00:00:00 2001 From: Diana Lau Date: Thu, 13 Jul 2017 22:35:01 -0400 Subject: [PATCH] Fix transaction --- lib/transaction.js | 8 +++++++- test/transaction.test.js | 41 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/lib/transaction.js b/lib/transaction.js index dfb9926..f01b406 100644 --- a/lib/transaction.js +++ b/lib/transaction.js @@ -85,7 +85,13 @@ Transaction.begin = function(connector, options, cb) { return cb(err); } var tx = connection; - if (!(connection instanceof Transaction)) { + + // When the connector and juggler node module have different version of this module as a dependency, + // the transaction is not an instanceof Transaction. + // i.e. (connection instanceof Transaction) == false + // Check for existence of required functions and properties, instead of prototype inheritance. + if (connection.connector == undefined || connection.connection == undefined || + connection.commit == undefined || connection.rollback == undefined) { tx = new Transaction(connector, connection); } cb(err, tx); diff --git a/test/transaction.test.js b/test/transaction.test.js index ef53528..f586c35 100644 --- a/test/transaction.test.js +++ b/test/transaction.test.js @@ -194,4 +194,45 @@ describe('transactions', function() { }); }); }); + + describe('transaction instance', function() { + function TestTransaction(connector, connection) { + this.connector = connector; + this.connection = connection; + } + Object.assign(TestTransaction.prototype, Transaction.prototype); + TestTransaction.prototype.foo = true; + function beginTransaction(isolationLevel, cb) { + return cb(null, new TestTransaction(testConnector, {})); + }; + + it('should do nothing when transaction is like a Transaction', function(done) { + testConnector.initialize(db, function(err, resultConnector) { + resultConnector.beginTransaction = beginTransaction; + Transaction.begin(resultConnector, Transaction.READ_COMMITTED, + function(err, result) { + if (err) done(err); + expect(result).to.be.instanceof(TestTransaction); + expect(result.foo).to.equal(true); + done(); + }); + }); + }); + + it('should create new instance when transaction is not like a Transaction', + function(done) { + testConnector.initialize(db, function(err, resultConnector) { + resultConnector.beginTransaction = beginTransaction; + delete TestTransaction.prototype.commit; + Transaction.begin(resultConnector, Transaction.READ_COMMITTED, + function(err, result) { + if (err) done(err); + expect(result).to.not.be.instanceof(TestTransaction); + expect(result).to.be.instanceof(Transaction); + expect(result.foo).to.equal(undefined); + done(); + }); + }); + }); + }); });