Skip to content

Commit

Permalink
refactor(pool): support a callback in connect
Browse files Browse the repository at this point in the history
  • Loading branch information
mbroadst committed Nov 5, 2019
1 parent 1147ebf commit 173f292
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
14 changes: 12 additions & 2 deletions lib/core/connection/pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -537,14 +537,20 @@ Pool.prototype.isDisconnected = function() {
/**
* Connect pool
*/
Pool.prototype.connect = function() {
Pool.prototype.connect = function(callback) {
if (this.state !== DISCONNECTED) {
throw new MongoError('connection in unlawful state ' + this.state);
}

stateTransition(this, CONNECTING);
createConnection(this, (err, conn) => {
if (err) {
if (typeof callback === 'function') {
this.destroy();
callback(err);
return;
}

if (this.state === CONNECTING) {
this.emit('error', err);
}
Expand All @@ -554,7 +560,11 @@ Pool.prototype.connect = function() {
}

stateTransition(this, CONNECTED);
this.emit('connect', this, conn);
if (typeof callback === 'function') {
callback(null, conn);
} else {
this.emit('connect', this, conn);
}

// create min connections
if (this.minSize) {
Expand Down
21 changes: 20 additions & 1 deletion test/core/functional/pool_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ describe('Pool tests', function() {
var pool = new Pool(null, {
host: this.configuration.host,
port: this.configuration.port,
socketTimeout: 3000,
socketTimeout: 500,
bson: new Bson(),
reconnect: false
});
Expand Down Expand Up @@ -1141,4 +1141,23 @@ describe('Pool tests', function() {
pool.connect();
}
});

it('should support callback mode for connect', {
metadata: { requires: { topology: 'single' } },
test: function(done) {
const pool = new Pool(null, {
host: this.configuration.host,
port: this.configuration.port,
bson: new Bson()
});

pool.on('connect', () => done(new Error('connect was emitted')));
pool.connect(err => {
expect(err).to.not.exist;
setTimeout(() => {
pool.destroy(true, done);
}, 100); // wait to ensure event is not emitted
});
}
});
});

0 comments on commit 173f292

Please sign in to comment.