Skip to content

Commit

Permalink
refactor: don't require a final callback for withConnection
Browse files Browse the repository at this point in the history
  • Loading branch information
mbroadst committed Dec 18, 2019
1 parent bc5c241 commit 56aeb52
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
10 changes: 6 additions & 4 deletions lib/cmap/connection_pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,10 +299,12 @@ class ConnectionPool extends EventEmitter {
// don't callback with `err` here, we might want to act upon it inside `fn`

fn(err, conn, (fnErr, result) => {
if (fnErr) {
callback(fnErr);
} else {
callback(undefined, result);
if (typeof callback === 'function') {
if (fnErr) {
callback(fnErr);
} else {
callback(undefined, result);
}
}

if (conn) {
Expand Down
30 changes: 30 additions & 0 deletions test/unit/cmap/connection_pool.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const ConnectionPool = require('../../../lib/cmap/connection_pool').ConnectionPo
const EventEmitter = require('events').EventEmitter;
const mock = require('mongodb-mock-server');
const BSON = require('bson');
const cmapEvents = require('../../../lib/cmap/events');

const chai = require('chai');
chai.use(require('../../functional/spec-runner/matcher').default);
Expand Down Expand Up @@ -115,6 +116,35 @@ describe('Connection Pool', function() {
cb(new Error('my great error'));
}, callback);
});

it('should still manage a connection if no callback is provided', function(done) {
server.setMessageHandler(request => {
const doc = request.document;
if (doc.ismaster) {
request.reply(mock.DEFAULT_ISMASTER_36);
}
});

const pool = new ConnectionPool(
Object.assign({ bson: new BSON(), maxPoolSize: 1 }, server.address())
);

const events = [];
pool.on('connectionCheckedOut', event => events.push(event));
pool.on('connectionCheckedIn', event => {
events.push(event);

expect(events).to.have.length(2);
expect(events[0]).to.be.instanceOf(cmapEvents.ConnectionCheckedOutEvent);
expect(events[1]).to.be.instanceOf(cmapEvents.ConnectionCheckedInEvent);
pool.close(done);
});

pool.withConnection((err, conn, cb) => {
expect(err).to.not.exist;
cb();
});
});
});

describe('spec tests', function() {
Expand Down

0 comments on commit 56aeb52

Please sign in to comment.