Spaces:
Running
Running
| import os | |
| import json | |
| import firebase_admin | |
| from firebase_admin import credentials, firestore | |
| COLLECTION_NAME = "CoconutAdvice" | |
| FIREBASE_CREDENTIALS_ENV = "FIREBASE_CREDENTIALS" | |
| def init_firestore(): | |
| """Initializes Firestore using a service account JSON provided via an environment variable. | |
| The environment variable should contain the full JSON contents of the Firebase service account | |
| key (the same JSON that would normally be stored in a file like `serviceAccountKey.json`). | |
| """ | |
| if not firebase_admin._apps: | |
| creds_json = os.getenv(FIREBASE_CREDENTIALS_ENV) | |
| if not creds_json: | |
| raise EnvironmentError( | |
| f"Environment variable {FIREBASE_CREDENTIALS_ENV} is required and must contain " | |
| "Firebase service account JSON." | |
| ) | |
| try: | |
| cred_dict = json.loads(creds_json) | |
| except json.JSONDecodeError as e: | |
| raise ValueError( | |
| f"Failed to parse JSON from {FIREBASE_CREDENTIALS_ENV}: {e}" | |
| ) from e | |
| cred = credentials.Certificate(cred_dict) | |
| firebase_admin.initialize_app(cred) | |
| return firestore.client() | |
| db = init_firestore() | |
| def get_advice_by_id(doc_id: str): | |
| """ | |
| Fetch one advisory record by document ID. | |
| """ | |
| doc = db.collection(COLLECTION_NAME).document(str(doc_id)).get() | |
| return doc.to_dict() if doc.exists else None |