Skip to content

Commit 56aeb52

Browse files
committed
refactor: don't require a final callback for withConnection
1 parent bc5c241 commit 56aeb52

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

lib/cmap/connection_pool.js

+6-4
Original file line numberDiff line numberDiff line change
@@ -299,10 +299,12 @@ class ConnectionPool extends EventEmitter {
299299
// don't callback with `err` here, we might want to act upon it inside `fn`
300300

301301
fn(err, conn, (fnErr, result) => {
302-
if (fnErr) {
303-
callback(fnErr);
304-
} else {
305-
callback(undefined, result);
302+
if (typeof callback === 'function') {
303+
if (fnErr) {
304+
callback(fnErr);
305+
} else {
306+
callback(undefined, result);
307+
}
306308
}
307309

308310
if (conn) {

test/unit/cmap/connection_pool.test.js

+30
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const ConnectionPool = require('../../../lib/cmap/connection_pool').ConnectionPo
66
const EventEmitter = require('events').EventEmitter;
77
const mock = require('mongodb-mock-server');
88
const BSON = require('bson');
9+
const cmapEvents = require('../../../lib/cmap/events');
910

1011
const chai = require('chai');
1112
chai.use(require('../../functional/spec-runner/matcher').default);
@@ -115,6 +116,35 @@ describe('Connection Pool', function() {
115116
cb(new Error('my great error'));
116117
}, callback);
117118
});
119+
120+
it('should still manage a connection if no callback is provided', function(done) {
121+
server.setMessageHandler(request => {
122+
const doc = request.document;
123+
if (doc.ismaster) {
124+
request.reply(mock.DEFAULT_ISMASTER_36);
125+
}
126+
});
127+
128+
const pool = new ConnectionPool(
129+
Object.assign({ bson: new BSON(), maxPoolSize: 1 }, server.address())
130+
);
131+
132+
const events = [];
133+
pool.on('connectionCheckedOut', event => events.push(event));
134+
pool.on('connectionCheckedIn', event => {
135+
events.push(event);
136+
137+
expect(events).to.have.length(2);
138+
expect(events[0]).to.be.instanceOf(cmapEvents.ConnectionCheckedOutEvent);
139+
expect(events[1]).to.be.instanceOf(cmapEvents.ConnectionCheckedInEvent);
140+
pool.close(done);
141+
});
142+
143+
pool.withConnection((err, conn, cb) => {
144+
expect(err).to.not.exist;
145+
cb();
146+
});
147+
});
118148
});
119149

120150
describe('spec tests', function() {

0 commit comments

Comments
 (0)