FastAPI-Backend-Models / services /database_service.py
Yassine Mhirsi
feat: Implement user management service with Supabase integration, including user registration, retrieval, and name update endpoints.
6e8d513
"""Database service for Supabase connection"""
import logging
from supabase import create_client, Client
from config import SUPABASE_URL, SUPABASE_KEY
logger = logging.getLogger(__name__)
class DatabaseService:
"""Service for managing Supabase database connection"""
def __init__(self):
self.client: Client | None = None
self.connected = False
def connect(self):
"""Initialize Supabase client connection"""
if self.connected and self.client:
logger.info("Database already connected")
return
if not SUPABASE_URL or not SUPABASE_KEY:
raise ValueError("SUPABASE_URL and SUPABASE_KEY must be set in environment variables")
try:
logger.info("Connecting to Supabase...")
self.client = create_client(SUPABASE_URL, SUPABASE_KEY)
self.connected = True
logger.info("✓ Successfully connected to Supabase")
except Exception as e:
logger.error(f"Error connecting to Supabase: {str(e)}")
raise RuntimeError(f"Failed to connect to Supabase: {str(e)}")
def get_client(self) -> Client:
"""Get Supabase client instance"""
if not self.connected or not self.client:
self.connect()
return self.client
def is_connected(self) -> bool:
"""Check if database is connected"""
return self.connected and self.client is not None
# Initialize singleton instance
database_service = DatabaseService()