File size: 1,101 Bytes
3ad0307
 
 
e2e8b20
 
 
3ad0307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import motor.motor_asyncio  
import os
import logging
from dotenv import load_dotenv

load_dotenv()

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

MONGO_URI = os.getenv("MONGO_URI")
if not MONGO_URI:
    raise ValueError("MONGO_URI is not set")

logger.info("Connecting to MongoDB")

client = None
db = None
users_collection = None

async def get_database():
    global client, db, users_collection

    if client is None:  
        try:
            logger.info("Connecting to MongoDB")
            client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI)
            db = client["fastapi_db"]
            users_collection = db["users"]
            logger.info("Successfully connected to MongoDB")
        except Exception as e:
            logger.error(f"MongoDB connection failed: {e}")
            raise

    return db

async def get_users_collection():
    await get_database()
    return users_collection

async def close_database():
    global client
    if client:
        logger.info("Closing MongoDB connection")
        client.close()
        client = None