knex/lib/transaction.js

76 lines
1.8 KiB
JavaScript
Raw Normal View History

(function(define) {
"use strict";
define(function(require, exports) {
var when = require('when');
var _ = require('underscore');
2013-09-04 20:47:27 -04:00
var Transaction = function(instance) {
2013-09-05 16:36:49 -04:00
this.client = instance.client;
2013-09-04 20:47:27 -04:00
};
2013-09-05 16:36:49 -04:00
Transaction.prototype = {
2013-09-05 16:36:49 -04:00
// Passed a `container` function, this method runs the current
// transaction, returning a promise.
run: function(container) {
return this.client.startTransaction()
.then(this.getContainerObject)
.then(this.initiateDeferred(container));
},
2013-09-05 16:36:49 -04:00
getContainerObject: function(connection) {
2013-09-05 16:36:49 -04:00
// The client we need to call `finishTransaction` on.
var client = this.client;
// The object passed around inside the transaction container.
var containerObj = {
2013-09-05 16:36:49 -04:00
commit: function(message) {
client.finishTransaction('commit', this, message);
},
2013-09-05 16:36:49 -04:00
rollback: function(error) {
client.finishTransaction('rollback', this, error);
},
2013-09-05 16:36:49 -04:00
// "rollback to"?
connection: connection
};
// Ensure the transacting object methods are bound with the correct context.
_.bindAll(containerObj, 'commit', 'rollback');
2013-09-05 16:36:49 -04:00
},
initiateDeferred: function(container) {
return function(containerObj) {
// Initiate a deferred object, so we know when the
// transaction completes or fails, we know what to do.
var dfd = containerObj.dfd = when.defer();
// Call the container with the transaction
// commit & rollback objects.
container(containerObj);
// Return the promise for the entire transaction.
return dfd.promise;
};
}
};
2013-09-04 20:47:27 -04:00
exports.Transaction = Transaction;
});
})(
typeof define === 'function' && define.amd ? define : function (factory) { factory(require, exports, module); }
);