Skip to content

Commit

Permalink
Separated functions, added tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Henry Mollman committed Oct 8, 2016
1 parent 6457073 commit f193650
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 8 deletions.
25 changes: 17 additions & 8 deletions lib/models/mongo/mongoose-control.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,12 @@ mongooseControl.start = function (cb) {
}

mongoose.connect(process.env.MONGO, mongooseOptions, cb)

mongoose.connection.on('disconnected', function () {
if (!mongoose.connection._hasOpened) {
log.fatal({message: 'Failed to connect to ' + process.env.MONGO}, 'failed to establish a connection to mongodb')
process.exit(1)
mongooseControl._exitIfFailedToOpen()
} else {
log.error({message: 'Lost connection to ' + process.env.MONGO})
setTimeout(function () {
if (!mongoose.connection.readyState) {
process.exit(1)
}
}, 10000)
mongooseControl._exitIfFailedToReconnect()
}
})
}
Expand All @@ -76,3 +71,17 @@ mongooseControl.stop = function (cb) {
})
})
}

mongooseControl._exitIfFailedToOpen = function () {
log.fatal({message: 'Failed to connect to ' + process.env.MONGO}, 'failed to establish a connection to mongodb')
process.exit(1)
}

mongooseControl._exitIfFailedToReconnect = function() {
log.error({message: 'Lost connection to ' + process.env.MONGO})
setTimeout(function () {
if (!mongoose.connection.readyState) {
process.exit(1)
}
}, 10000)
}
29 changes: 29 additions & 0 deletions unit/models/mongo/mongoose-control.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,5 +103,34 @@ describe('mongoose-control', function () {
done()
})
})

describe('handling mongodb disconnect events', function () {

beforeEach(function (done) {
sinon.stub(mongoose.connection, 'on').yields()
sinon.stub(mongooseControl, '_exitIfFailedToReconnect')
sinon.stub(mongooseControl, '_exitIfFailedToOpen')
done()
})

it('should exit if it cannot connect', function (done) {
mongooseControl.start(function (err) {
expect(err).to.not.exist()
sinon.assert.notCalled(mongooseControl._exitIfFailedToReconnect)
sinon.assert.calledOnce(mongooseControl._exitIfFailedToOpen)
done()
})
})

it('should attempt a retry if connection existed', function (done) {
mongoose.connection._hasOpened = true
mongooseControl.start(function (err) {
expect(err).to.not.exist()
sinon.assert.notCalled(mongooseControl._exitIfFailedToOpen)
sinon.assert.calledOnce(mongooseControl._exitIfFailedToReconnect)
done()
})
})
})
})
})

0 comments on commit f193650

Please sign in to comment.