Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pwhisenhunt/0c2369bc1114ece6b0eedde0887d9e8b to your computer and use it in GitHub Desktop.
Save pwhisenhunt/0c2369bc1114ece6b0eedde0887d9e8b to your computer and use it in GitHub Desktop.
blog-post-node-js-handle-connections-mongoose-initial-connection-retry
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