adds database mongoose event hooks
This commit is contained in:
		@@ -1,10 +1,9 @@
 | 
			
		||||
// aqui la conexión con MongoDB, usando mongoose o cualquier otro odm que vaya a usar
 | 
			
		||||
// las conexión a bases de datos normalmente deberían ser Singleton para reutilizar la conexión
 | 
			
		||||
// motivo: pues no saturar la base de datos ni saturarla con multiples conexiones
 | 
			
		||||
import mongoose from 'mongoose';
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
export class DatabaseConnection {
 | 
			
		||||
    private static instance: DatabaseConnection;
 | 
			
		||||
    // private isConnected: boolean = false; // a implementar
 | 
			
		||||
    private isConnected: boolean = false; // a implementar
 | 
			
		||||
  
 | 
			
		||||
    private constructor() {}
 | 
			
		||||
  
 | 
			
		||||
@@ -14,4 +13,43 @@ export class DatabaseConnection {
 | 
			
		||||
      }
 | 
			
		||||
      return DatabaseConnection.instance;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public async connect(): Promise<void> {
 | 
			
		||||
      if (this.isConnected) {
 | 
			
		||||
        console.log("database is already connected")
 | 
			
		||||
        return;
 | 
			
		||||
      }
 | 
			
		||||
  
 | 
			
		||||
      try {
 | 
			
		||||
        await mongoose.connect(config.mongodbUri, {
 | 
			
		||||
          maxPoolSize: 10,
 | 
			
		||||
          serverSelectionTimeoutMS: 5000,
 | 
			
		||||
          socketTimeoutMS: 45000,
 | 
			
		||||
          bufferCommands: false,
 | 
			
		||||
        });
 | 
			
		||||
  
 | 
			
		||||
        this.isConnected = true;
 | 
			
		||||
        console.log("database connected")
 | 
			
		||||
  
 | 
			
		||||
        mongoose.connection.on('error', (error) => {
 | 
			
		||||
          console.log('MongoDB connection error', { error });
 | 
			
		||||
          this.isConnected = false;
 | 
			
		||||
        });
 | 
			
		||||
  
 | 
			
		||||
        mongoose.connection.on('disconnected', () => {
 | 
			
		||||
          console.log('MongoDB connection disconnected', { error });
 | 
			
		||||
          this.isConnected = false;
 | 
			
		||||
        });
 | 
			
		||||
  
 | 
			
		||||
        mongoose.connection.on('reconnected', () => {
 | 
			
		||||
          console.log('MongoDB connection reconnected');
 | 
			
		||||
          this.isConnected = true;
 | 
			
		||||
        });
 | 
			
		||||
  
 | 
			
		||||
      } catch (error) {
 | 
			
		||||
        console.log('MongoDB Failed to connect', { error });
 | 
			
		||||
        this.isConnected = false;
 | 
			
		||||
        throw error;
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user