11const util = require ( "node:util" ) ;
22const mongoose = require ( "mongoose" ) ;
33const debug = require ( "../../lib/debug" ) ;
4+ const { sleep } = require ( "../../lib/util" ) ;
45const validateConnectionOptions = require ( "./connection-validator" ) ;
56
67
@@ -44,11 +45,12 @@ module.exports = class MongooseStore {
4445 * @return {resource } a (mongoose) connection instance
4546 */
4647 async connect ( ) {
48+ let dsn ;
49+ let attempts = 0 ;
4750 const options = this . #options;
51+ const maxAttempts = this . #options. maxConnectionAttempts || 5 ;
4852 const { host, port, username, password, dbName, enableDebugging } = options ;
4953
50- let dsn ;
51-
5254 if ( options . url ?. trim ( ) ?. length > 0 ) {
5355 dsn = options . url ;
5456 } else {
@@ -67,16 +69,28 @@ module.exports = class MongooseStore {
6769
6870 mongoose . set ( "debug" , enableDebugging ) ;
6971
70- try {
71- debug ( "Connecting to MongoDB..." ) ;
72+ while ( attempts < maxAttempts ) {
73+ try {
74+ debug ( "Connecting to MongoDB..." ) ;
7275
73- this . #db = mongoose . createConnection ( dsn , { } ) ;
76+ this . #db = mongoose . createConnection ( dsn , { } ) ;
7477
75- debug ( "MongoDB connection established" ) ;
78+ debug ( "MongoDB connection established" ) ;
7679
77- return this . #db;
78- } catch ( e ) {
79- debug ( `Mongoose connection error: ${ util . inspect ( e ) } ` ) ;
80+ return this . #db;
81+ } catch ( e ) {
82+ attempts ++ ;
83+
84+ debug ( `Mongoose connection error: ${ util . inspect ( e ) } ` ) ;
85+ debug ( `Retrying connection to MongoDB (${ attempts } /${ maxAttempts } ) attempts` ) ;
86+
87+ if ( attempts === maxAttempts ) {
88+ debug ( `Failed to connect to MongoDB after ${ maxAttempts } attempts. Exiting...` ) ;
89+ process . exit ( 1 ) ;
90+ }
91+
92+ await sleep ( 1000 * attempts ) ; // Exponential backoff
93+ }
8094 }
8195 }
8296
@@ -145,6 +159,10 @@ module.exports = class MongooseStore {
145159
146160 debug ( "Mongoose connection options validated." ) ;
147161
148- return { ...validatedOptions , url : options ?. url } ;
162+ return {
163+ ...validatedOptions ,
164+ url : options ?. url ,
165+ maxConnectionAttempts : options ?. maxConnectionAttempts ,
166+ } ;
149167 }
150168} ;
0 commit comments