Skip to content

Commit

Permalink
Add is_initialized() method to the MongoDB class
Browse files Browse the repository at this point in the history
This is to ensure that we are calling `MongoDB.close()` only if the client has been properly initialized.
  • Loading branch information
pkhalaj committed Jun 2, 2024
1 parent 7c89d03 commit 5f99c38
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion trolldb/database/mongodb.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,11 @@ async def initialize(cls, database_config: DatabaseConfig):
cls.__main_collection = cls.__main_database.get_collection(database_config.main_collection_name)
logger.info("MongoDB is successfully initialized.")

@classmethod
def is_initialized(cls) -> bool:
"""Checks if the motor client is initialized."""
return cls.__client is not None

@classmethod
def close(cls) -> None:
"""Closes the motor client."""
Expand Down Expand Up @@ -308,5 +313,8 @@ async def mongodb_context(database_config: DatabaseConfig) -> AsyncGenerator:
await MongoDB.initialize(database_config)
yield
finally:
MongoDB.close()
if MongoDB.is_initialized():
MongoDB.close()
else:
logger.info("The MongoDB client was not initialized!")
logger.info("The MongoDB context manager is successfully closed.")

0 comments on commit 5f99c38

Please sign in to comment.