File tree Expand file tree Collapse file tree 2 files changed +46
-8
lines changed Expand file tree Collapse file tree 2 files changed +46
-8
lines changed Original file line number Diff line number Diff line change @@ -52,17 +52,12 @@ mongooseControl.start = function (cb) {
52
52
}
53
53
54
54
mongoose . connect ( process . env . MONGO , mongooseOptions , cb )
55
+
55
56
mongoose . connection . on ( 'disconnected' , function ( ) {
56
57
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 ( )
59
59
} 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 ( )
66
61
}
67
62
} )
68
63
}
@@ -76,3 +71,17 @@ mongooseControl.stop = function (cb) {
76
71
} )
77
72
} )
78
73
}
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
+ }
Original file line number Diff line number Diff line change @@ -103,5 +103,34 @@ describe('mongoose-control', function () {
103
103
done ( )
104
104
} )
105
105
} )
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
+ } )
106
135
} )
107
136
} )
You can’t perform that action at this time.
0 commit comments