Last active
May 25, 2020 17:31
-
-
Save pwhisenhunt/0c2369bc1114ece6b0eedde0887d9e8b to your computer and use it in GitHub Desktop.
blog-post-node-js-handle-connections-mongoose-initial-connection-retry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let numberOfMongooseRetries = 1; | |
const THIRTY_SECONDS = 30000; | |
const MAX_DELAY_TO_RECONNECT = THIRTY_SECONDS; | |
async function connectToMongoose() { | |
console.log(`attempt ${numberOfMongooseRetries} to connect to mongo`); | |
try { | |
await mongoose.connect(env.MONGO_DB_CONNECTION_STRING, { useNewUrlParser: true }) | |
} | |
catch (err) { | |
// Note: this is where you would send errors to your error tracker | |
console.error('failed to intially connect to mongo', err); | |
const timeUntilRetrying = Math.min(MAX_DELAY_TO_RECONNECT, (Math.pow(2, numberOfMongooseRetries) * 1000)); | |
console.log(`will try reconnecting in ${timeUntilRetrying / 1000} seconds`); | |
setTimeout(() => { | |
numberOfMongooseRetries++; | |
connectToMongoose(); | |
}, timeUntilRetrying); | |
} | |
} | |
connectToMongoose(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment