From b6670f5d6c26f9858e01b4dbe379b50a3063295d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrg=20Lehni?= Date: Thu, 31 Aug 2017 16:43:51 +0200 Subject: [PATCH] Transaction: Support moving timeout to connector --- lib/transaction.js | 22 ++++++++++++++++++++++ package.json | 3 ++- 2 files changed, 24 insertions(+), 1 deletion(-) 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",