Skip to content

Commit f193650

Browse files
author
Henry Mollman
committed
Separated functions, added tests
1 parent 6457073 commit f193650

File tree

2 files changed

+46
-8
lines changed

2 files changed

+46
-8
lines changed

lib/models/mongo/mongoose-control.js

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -52,17 +52,12 @@ mongooseControl.start = function (cb) {
5252
}
5353

5454
mongoose.connect(process.env.MONGO, mongooseOptions, cb)
55+
5556
mongoose.connection.on('disconnected', function () {
5657
if (!mongoose.connection._hasOpened) {
57-
log.fatal({message: 'Failed to connect to ' + process.env.MONGO}, 'failed to establish a connection to mongodb')
58-
process.exit(1)
58+
mongooseControl._exitIfFailedToOpen()
5959
} else {
60-
log.error({message: 'Lost connection to ' + process.env.MONGO})
61-
setTimeout(function () {
62-
if (!mongoose.connection.readyState) {
63-
process.exit(1)
64-
}
65-
}, 10000)
60+
mongooseControl._exitIfFailedToReconnect()
6661
}
6762
})
6863
}
@@ -76,3 +71,17 @@ mongooseControl.stop = function (cb) {
7671
})
7772
})
7873
}
74+
75+
mongooseControl._exitIfFailedToOpen = function () {
76+
log.fatal({message: 'Failed to connect to ' + process.env.MONGO}, 'failed to establish a connection to mongodb')
77+
process.exit(1)
78+
}
79+
80+
mongooseControl._exitIfFailedToReconnect = function() {
81+
log.error({message: 'Lost connection to ' + process.env.MONGO})
82+
setTimeout(function () {
83+
if (!mongoose.connection.readyState) {
84+
process.exit(1)
85+
}
86+
}, 10000)
87+
}

unit/models/mongo/mongoose-control.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,5 +103,34 @@ describe('mongoose-control', function () {
103103
done()
104104
})
105105
})
106+
107+
describe('handling mongodb disconnect events', function () {
108+
109+
beforeEach(function (done) {
110+
sinon.stub(mongoose.connection, 'on').yields()
111+
sinon.stub(mongooseControl, '_exitIfFailedToReconnect')
112+
sinon.stub(mongooseControl, '_exitIfFailedToOpen')
113+
done()
114+
})
115+
116+
it('should exit if it cannot connect', function (done) {
117+
mongooseControl.start(function (err) {
118+
expect(err).to.not.exist()
119+
sinon.assert.notCalled(mongooseControl._exitIfFailedToReconnect)
120+
sinon.assert.calledOnce(mongooseControl._exitIfFailedToOpen)
121+
done()
122+
})
123+
})
124+
125+
it('should attempt a retry if connection existed', function (done) {
126+
mongoose.connection._hasOpened = true
127+
mongooseControl.start(function (err) {
128+
expect(err).to.not.exist()
129+
sinon.assert.notCalled(mongooseControl._exitIfFailedToOpen)
130+
sinon.assert.calledOnce(mongooseControl._exitIfFailedToReconnect)
131+
done()
132+
})
133+
})
134+
})
106135
})
107136
})

0 commit comments

Comments
 (0)