Skip to content

Commit

Permalink
feat: append recommendations into DB
Browse files Browse the repository at this point in the history
  • Loading branch information
Hk669 committed Jul 17, 2024
1 parent 98c7ec7 commit f2cc616
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
GithubUser,
RepositoryRecommendation,
get_user_collection,
append_recommendations_to_db,
# check_daily_limit
)
from .db import (
Expand Down
10 changes: 8 additions & 2 deletions src/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from .user_data import get_repos
from src.db import (recommend,
get_topic_based_recommendations)
from src.models import User, GithubUser, get_user_collection
from src.models import User, GithubUser, get_user_collection, append_recommendations_to_db

load_dotenv()
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -212,8 +212,14 @@ async def get_recommendations(request: Request, current_user: dict = Depends(get
if not unique_recommendations:
return {'recommendations': [], 'message': 'No recommendations found'}

rec_name = f"Recommendations for {username} - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
rec_id = append_recommendations_to_db(username, unique_recommendations, rec_name)

# update_daily_limit(username) # updates the daily limit of the user.
return {'recommendations': unique_recommendations[::-1]}
return {
'recommendations': unique_recommendations[::-1],
'recommendations_id': rec_id
}
except Exception as e:
logger.error(f"Error: {str(e)}")
raise HTTPException(status_code=500, detail="An error occurred while generating recommendations")
Expand Down
61 changes: 61 additions & 0 deletions src/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import Optional, List
from motor.motor_asyncio import AsyncIOMotorClient
import os
import uuid
import logging
from dotenv import load_dotenv
load_dotenv()
Expand All @@ -18,6 +19,9 @@
async def get_user_collection():
return db['users']

async def get_recommendations_collection():
return db['recommendations']


class User(BaseModel):
username: str
Expand Down Expand Up @@ -76,6 +80,63 @@ class RepositoryRecommendation(BaseModel):
updated_at: str
topics: str


def append_recommendations_to_db(username, recommendations, recommendation_name):
try:
user_recommenations_coll = db['user_recommendations']
recommendations_collection = db['recommendations']

except Exception as e:
logger.error(f"Failed to fetch recommendations from DB: {str(e)}")
raise ValueError("Failed to fetch recommendations from DB")

recommendation_id = str(uuid.uuid4())
try:
recommendations_collection.insert_one({
"recommendation_id": recommendation_id,
"recommendations": recommendations
})

except Exception as e:
logger.error(f"Failed to save recommendations to DB: {str(e)}")
raise ValueError("Failed to save recommendations to DB")

try:
user_recommenations_coll.update_one(
{"username": username},
{"$push": {
"recommendation_refs": {
"recommendation_id": recommendation_id,
"recommendation_name": recommendation_name
}
}},
upsert=True
)

return recommendation_id
except Exception as e:
logger.error(f"Failed to save user recommendations to DB: {str(e)}")
raise ValueError("Failed to save user recommendations to DB")


def get_recommendation_by_id(recommendation_id):
try:
recommendations_collection = db['recommendations']
recommendation_data = recommendations_collection.find_one({"recommendation_id": recommendation_id})

if not recommendation_data:
return None

return {
"recommendation_id": recommendation_id,
"recommendations": recommendation_data["recommendations"]
}

except Exception as e:
logger.error(f"Failed to get recommendation from DB: {str(e)}")
raise ValueError("Failed to get recommendation from DB")


# TODO: v2
# def update_daily_limit_to_all_users():
# try:
Expand Down

0 comments on commit f2cc616

Please sign in to comment.