Skip to content

Commit eca2ea0

Browse files
cody-greenebrianc
authored andcommitted
emit "connect" event only on success and avoid double callback (brianc#22)
* fail: "connect" event only on success Double callback invocation will also cause this to fail. * avoid double callback: _create If `client.connect` returns an error, then the callback for `Pool#_create` is only invoked once. Also the `connect` event is only emitted on a successful connection, the client is otherwise rather useless. * legacy compat; don't use Object.assign * legacy compat; events.EventEmitter
1 parent 51fb7db commit eca2ea0

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed

index.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,14 @@ Pool.prototype._create = function (cb) {
4040
}.bind(this))
4141

4242
client.connect(function (err) {
43-
this.log('client connected')
44-
this.emit('connect', client)
4543
if (err) {
4644
this.log('client connection error:', err)
4745
cb(err)
46+
} else {
47+
this.log('client connected')
48+
this.emit('connect', client)
49+
cb(null, client)
4850
}
49-
cb(err, err ? null : client)
5051
}.bind(this))
5152
}
5253

test/events.js

+28-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
var expect = require('expect.js')
2-
2+
var EventEmitter = require('events').EventEmitter
33
var describe = require('mocha').describe
44
var it = require('mocha').it
5-
5+
var objectAssign = require('object-assign')
66
var Pool = require('../')
77

88
describe('events', function () {
@@ -22,6 +22,24 @@ describe('events', function () {
2222
})
2323
})
2424

25+
it('emits "connect" only with a successful connection', function (done) {
26+
var pool = new Pool({
27+
// This client will always fail to connect
28+
Client: mockClient({
29+
connect: function (cb) {
30+
process.nextTick(function () { cb(new Error('bad news')) })
31+
}
32+
})
33+
})
34+
pool.on('connect', function () {
35+
throw new Error('should never get here')
36+
})
37+
pool._create(function (err) {
38+
if (err) done()
39+
else done(new Error('expected failure'))
40+
})
41+
})
42+
2543
it('emits acquire every time a client is acquired', function (done) {
2644
var pool = new Pool()
2745
var acquireCount = 0
@@ -43,3 +61,11 @@ describe('events', function () {
4361
}, 40)
4462
})
4563
})
64+
65+
function mockClient (methods) {
66+
return function () {
67+
var client = new EventEmitter()
68+
objectAssign(client, methods)
69+
return client
70+
}
71+
}

0 commit comments

Comments
 (0)