Transaction: Support moving timeout to connector

This commit is contained in:
Jürg Lehni 2017-08-31 16:43:51 +02:00
parent fa6f51d198
commit b6670f5d6c
2 changed files with 24 additions and 1 deletions

View File

@ -8,6 +8,7 @@ var assert = require('assert');
var util = require('util'); var util = require('util');
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var debug = require('debug')('loopback:connector:transaction'); var debug = require('debug')('loopback:connector:transaction');
var uuid = require('uuid');
module.exports = Transaction; module.exports = Transaction;
@ -94,6 +95,27 @@ Transaction.begin = function(connector, options, cb) {
connection.commit == undefined || connection.rollback == undefined) { connection.commit == undefined || connection.rollback == undefined) {
tx = new Transaction(connector, connection); tx = new Transaction(connector, connection);
} }
// Set an informational transaction id
tx.id = uuid.v1();
// NOTE(lehni) Handling of transaction timeouts here only works with recent
// versions of `loopback-datasource-juggler` which make its own handling of
// timeouts conditional based on the absence of an already set `tx.timeout`,
// see: https://github.com/strongloop/loopback-datasource-juggler/pull/1484
if (options.timeout) {
tx.timeout = setTimeout(function() {
var context = {
transaction: tx,
operation: 'timeout',
};
tx.notifyObserversOf('timeout', context, function(err) {
if (!err) {
tx.rollback(function() {
debug('Transaction %s is rolled back due to timeout', tx.id);
});
}
});
}, options.timeout);
}
cb(err, tx); cb(err, tx);
}); });
}; };

View File

@ -26,7 +26,8 @@
"bluebird": "^3.4.6", "bluebird": "^3.4.6",
"debug": "^2.2.0", "debug": "^2.2.0",
"msgpack5": "^3.4.1", "msgpack5": "^3.4.1",
"strong-globalize": "^2.5.8" "strong-globalize": "^2.5.8",
"uuid": "^3.0.1"
}, },
"devDependencies": { "devDependencies": {
"chai": "~3.5.0", "chai": "~3.5.0",