Make sure error events are emitted by data source

This commit is contained in:
Raymond Feng 2014-08-27 09:14:17 -07:00
parent 693a38fed5
commit fde5b426e4
2 changed files with 47 additions and 0 deletions

View File

@ -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();
}

View File

@ -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');