Skip to content

Instantly share code, notes, and snippets.

@un4ckn0wl3z
Last active August 23, 2023 07:05
Show Gist options
  • Save un4ckn0wl3z/149bfef554c5eb696768d3ff536f070d to your computer and use it in GitHub Desktop.
Save un4ckn0wl3z/149bfef554c5eb696768d3ff536f070d to your computer and use it in GitHub Desktop.
import { Logger, Module } from '@nestjs/common';
import { MongoClient } from 'mongodb';
import { MongoProperty } from './mongo-property.interface';
@Module({
providers: [
{
provide: 'PAYMENT_DATABASE_CONNECTION',
useFactory: async (): Promise<MongoProperty> => {
const maxReconnectAttempts = 5;
const reconnectInterval = 3000; // 3 seconds
let currentReconnectAttempts = 0;
const connectWithRetry = async (): Promise<MongoProperty> => {
try {
const client = new MongoClient(process.env.DATABASE_URL);
await client.connect();
_logger.log('Connected to MongoDB');
return {
connection: client,
db: client.db(process.env.DATABASE_NAME)
} // Return the MongoDB database instance
} catch (error) {
if (currentReconnectAttempts < maxReconnectAttempts) {
_logger.log('Failed to connect to MongoDB. Retrying...');
currentReconnectAttempts++;
setTimeout(connectWithRetry, reconnectInterval);
} else {
_logger.error('Failed to connect to MongoDB after multiple attempts.');
throw error;
}
}
};
return connectWithRetry();
},
},
],
exports: ['PAYMENT_DATABASE_CONNECTION'],
})
export class DatabaseModule {}
const _logger = new Logger(DatabaseModule.name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment