diff --git a/lib/transaction.js b/lib/transaction.js index f01b406..4831721 100644 --- a/lib/transaction.js +++ b/lib/transaction.js @@ -8,6 +8,7 @@ var assert = require('assert'); var util = require('util'); var EventEmitter = require('events').EventEmitter; var debug = require('debug')('loopback:connector:transaction'); +var uuid = require('uuid'); module.exports = Transaction; @@ -94,6 +95,27 @@ Transaction.begin = function(connector, options, cb) { connection.commit == undefined || connection.rollback == undefined) { 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); }); }; diff --git a/package.json b/package.json index 65096e2..2645265 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,8 @@ "bluebird": "^3.4.6", "debug": "^2.2.0", "msgpack5": "^3.4.1", - "strong-globalize": "^2.5.8" + "strong-globalize": "^2.5.8", + "uuid": "^3.0.1" }, "devDependencies": { "chai": "~3.5.0",