From fde5b426e4b499c57f6279087a87c1404710b6bf Mon Sep 17 00:00:00 2001 From: Raymond Feng Date: Wed, 27 Aug 2014 09:14:17 -0700 Subject: [PATCH] Make sure error events are emitted by data source --- lib/datasource.js | 15 +++++++++++++++ test/loopback-dl.test.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/lib/datasource.js b/lib/datasource.js index ffd2608c..1730051a 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -291,6 +291,7 @@ DataSource.prototype.setup = function (name, settings) { connector = result.connector; if (!connector) { console.error(result.error); + this.emit('error', new Error(result.error)); return; } } @@ -310,6 +311,7 @@ DataSource.prototype.setup = function (name, settings) { } else { // The connection fails, let's report it and hope it will be recovered in the next call console.error('Connection fails: ', err, '\nIt will be retried for the next request.'); + this.emit('error', err); this.connecting = false; } @@ -1878,6 +1880,19 @@ DataSource.prototype.ready = function (obj, args) { }; this.once('connected', onConnected); this.once('error', onError); + + // Set up a timeout to cancel the invocation + var timeout = this.settings.connectionTimeout || 5000; + setTimeout(function() { + self.removeListener('error', onError); + self.removeListener('connected', onConnected); + var params = [].slice.call(args); + var cb = params.pop(); + if (typeof cb === 'function') { + cb(new Error('Timeout in connecting after ' + timeout + ' ms')); + } + }, timeout); + if (!this.connecting) { this.connect(); } diff --git a/test/loopback-dl.test.js b/test/loopback-dl.test.js index 972d7aab..940c9a79 100644 --- a/test/loopback-dl.test.js +++ b/test/loopback-dl.test.js @@ -245,6 +245,38 @@ describe('ModelBuilder define model', function () { }); +describe('DataSource ping', function() { + var ds = new DataSource('memory'); + ds.settings.connectionTimeout = 50; // ms + ds.connector.connect = function(cb) { + // Mock up the long delay + setTimeout(cb, 100); + }; + ds.connector.ping = function(cb) { + cb(new Error('bad connection 2')); + } + + it('should report connection errors during ping', function(done) { + ds.ping(function(err) { + (!!err).should.be.true; + err.message.should.be.eql('bad connection 2'); + done(); + }); + }); + + it('should cancel invocation after timeout', function(done) { + ds.connected = false; // Force connect + var Post = ds.define('Post', { + title: { type: String, length: 255 } + }); + Post.create(function(err) { + (!!err).should.be.true; + err.message.should.be.eql('Timeout in connecting after 50 ms'); + done(); + }); + }); +}); + describe('DataSource define model', function () { it('should be able to define plain models', function () { var ds = new DataSource('memory');