Skip to content

Instantly share code, notes, and snippets.

@gnmonsour
Last active June 20, 2022 00:17
Show Gist options
  • Save gnmonsour/a1d108e4d5228988f7c20d2671beb739 to your computer and use it in GitHub Desktop.
Save gnmonsour/a1d108e4d5228988f7c20d2671beb739 to your computer and use it in GitHub Desktop.
const mongoose = require('mongoose');
const {
MONGO_IP,
MONGO_PORT,
MONGO_USER,
MONGO_PASSWORD,
} = require('./config/config');
const mongoURL = `mongodb://${MONGO_USER}:${MONGO_PASSWORD}@${MONGO_IP}:${MONGO_PORT}/?authSource=admin`;
// console.log(mongoURL);
let retryAttempts = 0;
const connectWithRetry = () => {
retryAttempts++;
mongoose
.connect(mongoURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
})
.then(() =>
console.log('connected to mongo', `on attempt ${retryAttempts}`)
)
.catch((err) => {
console.log(`error on mongoose connection ${err}\nRetrying ...`);
if (retryAttempts < 4) {
setTimeout(connectWithRetry, 5000);
} else {
console.log(
`bailing out on connection attempts after ${retryAttempts}, escalate to devOps`
);
}
});
};
connectWithRetry();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment