mongog setup
This commit is contained in:
1
backend/routers/__init__.py
Normal file
1
backend/routers/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# Routers package
|
||||
BIN
backend/routers/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
backend/routers/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/routers/__pycache__/entries.cpython-312.pyc
Normal file
BIN
backend/routers/__pycache__/entries.cpython-312.pyc
Normal file
Binary file not shown.
BIN
backend/routers/__pycache__/users.cpython-312.pyc
Normal file
BIN
backend/routers/__pycache__/users.cpython-312.pyc
Normal file
Binary file not shown.
165
backend/routers/entries.py
Normal file
165
backend/routers/entries.py
Normal file
@@ -0,0 +1,165 @@
|
||||
"""Journal entry routes"""
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from db import get_database
|
||||
from models import JournalEntryCreate, JournalEntryUpdate
|
||||
from datetime import datetime
|
||||
from typing import List
|
||||
from bson import ObjectId
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/{user_id}", response_model=dict)
|
||||
async def create_entry(user_id: str, entry_data: JournalEntryCreate):
|
||||
"""Create a new journal entry"""
|
||||
db = get_database()
|
||||
|
||||
try:
|
||||
entry_doc = {
|
||||
"userId": user_id,
|
||||
"title": entry_data.title,
|
||||
"content": entry_data.content,
|
||||
"mood": entry_data.mood,
|
||||
"tags": entry_data.tags or [],
|
||||
"isPublic": entry_data.isPublic,
|
||||
"createdAt": datetime.utcnow(),
|
||||
"updatedAt": datetime.utcnow()
|
||||
}
|
||||
|
||||
result = db.entries.insert_one(entry_doc)
|
||||
entry_doc["id"] = str(result.inserted_id)
|
||||
|
||||
return {
|
||||
"id": entry_doc["id"],
|
||||
"message": "Entry created successfully"
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{user_id}")
|
||||
async def get_user_entries(user_id: str, limit: int = 50, skip: int = 0):
|
||||
"""Get all entries for a user (paginated, most recent first)"""
|
||||
db = get_database()
|
||||
|
||||
try:
|
||||
entries = list(
|
||||
db.entries.find(
|
||||
{"userId": user_id}
|
||||
).sort("createdAt", -1).skip(skip).limit(limit)
|
||||
)
|
||||
|
||||
for entry in entries:
|
||||
entry["id"] = str(entry["_id"])
|
||||
del entry["_id"]
|
||||
|
||||
total = db.entries.count_documents({"userId": user_id})
|
||||
|
||||
return {
|
||||
"entries": entries,
|
||||
"total": total,
|
||||
"skip": skip,
|
||||
"limit": limit
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{user_id}/{entry_id}")
|
||||
async def get_entry(user_id: str, entry_id: str):
|
||||
"""Get a specific entry"""
|
||||
db = get_database()
|
||||
|
||||
try:
|
||||
entry = db.entries.find_one({
|
||||
"_id": ObjectId(entry_id),
|
||||
"userId": user_id
|
||||
})
|
||||
|
||||
if not entry:
|
||||
raise HTTPException(status_code=404, detail="Entry not found")
|
||||
|
||||
entry["id"] = str(entry["_id"])
|
||||
del entry["_id"]
|
||||
|
||||
return entry
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/{user_id}/{entry_id}")
|
||||
async def update_entry(user_id: str, entry_id: str, entry_data: JournalEntryUpdate):
|
||||
"""Update a journal entry"""
|
||||
db = get_database()
|
||||
|
||||
try:
|
||||
update_data = entry_data.model_dump(exclude_unset=True)
|
||||
update_data["updatedAt"] = datetime.utcnow()
|
||||
|
||||
result = db.entries.update_one(
|
||||
{
|
||||
"_id": ObjectId(entry_id),
|
||||
"userId": user_id
|
||||
},
|
||||
{"$set": update_data}
|
||||
)
|
||||
|
||||
if result.matched_count == 0:
|
||||
raise HTTPException(status_code=404, detail="Entry not found")
|
||||
|
||||
return {"message": "Entry updated successfully"}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/{user_id}/{entry_id}")
|
||||
async def delete_entry(user_id: str, entry_id: str):
|
||||
"""Delete a journal entry"""
|
||||
db = get_database()
|
||||
|
||||
try:
|
||||
result = db.entries.delete_one({
|
||||
"_id": ObjectId(entry_id),
|
||||
"userId": user_id
|
||||
})
|
||||
|
||||
if result.deleted_count == 0:
|
||||
raise HTTPException(status_code=404, detail="Entry not found")
|
||||
|
||||
return {"message": "Entry deleted successfully"}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{user_id}/date/{date_str}")
|
||||
async def get_entries_by_date(user_id: str, date_str: str):
|
||||
"""Get entries for a specific date (format: YYYY-MM-DD)"""
|
||||
db = get_database()
|
||||
|
||||
try:
|
||||
from datetime import datetime as dt
|
||||
|
||||
# Parse date
|
||||
target_date = dt.strptime(date_str, "%Y-%m-%d")
|
||||
next_date = dt.fromtimestamp(target_date.timestamp() + 86400)
|
||||
|
||||
entries = list(
|
||||
db.entries.find({
|
||||
"userId": user_id,
|
||||
"createdAt": {
|
||||
"$gte": target_date,
|
||||
"$lt": next_date
|
||||
}
|
||||
}).sort("createdAt", -1)
|
||||
)
|
||||
|
||||
for entry in entries:
|
||||
entry["id"] = str(entry["_id"])
|
||||
del entry["_id"]
|
||||
|
||||
return {"entries": entries, "date": date_str}
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=400, detail="Invalid date format. Use YYYY-MM-DD")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
99
backend/routers/users.py
Normal file
99
backend/routers/users.py
Normal file
@@ -0,0 +1,99 @@
|
||||
"""User management routes"""
|
||||
from fastapi import APIRouter, HTTPException, Header
|
||||
from pymongo.errors import DuplicateKeyError
|
||||
from db import get_database
|
||||
from models import UserCreate, UserUpdate, User
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/register", response_model=dict)
|
||||
async def register_user(user_data: UserCreate):
|
||||
"""
|
||||
Register a new user (called after Firebase Google Auth)
|
||||
Stores user profile in MongoDB
|
||||
"""
|
||||
db = get_database()
|
||||
|
||||
try:
|
||||
user_doc = {
|
||||
"email": user_data.email,
|
||||
"displayName": user_data.displayName or user_data.email.split("@")[0],
|
||||
"photoURL": user_data.photoURL,
|
||||
"createdAt": datetime.utcnow(),
|
||||
"updatedAt": datetime.utcnow(),
|
||||
"theme": "light"
|
||||
}
|
||||
|
||||
result = db.users.insert_one(user_doc)
|
||||
user_doc["id"] = str(result.inserted_id)
|
||||
|
||||
return {
|
||||
"id": user_doc["id"],
|
||||
"email": user_doc["email"],
|
||||
"displayName": user_doc["displayName"],
|
||||
"message": "User registered successfully"
|
||||
}
|
||||
except DuplicateKeyError:
|
||||
raise HTTPException(status_code=400, detail="User already exists")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/by-email/{email}", response_model=dict)
|
||||
async def get_user_by_email(email: str):
|
||||
"""Get user profile by email (called after Firebase Auth)"""
|
||||
db = get_database()
|
||||
|
||||
user = db.users.find_one({"email": email})
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
user["id"] = str(user["_id"])
|
||||
return user
|
||||
|
||||
|
||||
@router.put("/update/{user_id}", response_model=dict)
|
||||
async def update_user(user_id: str, user_data: UserUpdate):
|
||||
"""Update user profile"""
|
||||
db = get_database()
|
||||
from bson import ObjectId
|
||||
|
||||
try:
|
||||
update_data = user_data.model_dump(exclude_unset=True)
|
||||
update_data["updatedAt"] = datetime.utcnow()
|
||||
|
||||
result = db.users.update_one(
|
||||
{"_id": ObjectId(user_id)},
|
||||
{"$set": update_data}
|
||||
)
|
||||
|
||||
if result.matched_count == 0:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
return {"message": "User updated successfully"}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/{user_id}")
|
||||
async def delete_user(user_id: str):
|
||||
"""Delete user account and all associated data"""
|
||||
db = get_database()
|
||||
from bson import ObjectId
|
||||
|
||||
try:
|
||||
# Delete user
|
||||
db.users.delete_one({"_id": ObjectId(user_id)})
|
||||
|
||||
# Delete all entries by user
|
||||
db.entries.delete_many({"userId": user_id})
|
||||
|
||||
# Delete user settings
|
||||
db.settings.delete_one({"userId": user_id})
|
||||
|
||||
return {"message": "User and associated data deleted"}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
Reference in New Issue
Block a user