-
Notifications
You must be signed in to change notification settings - Fork 23
feat(user): add user services endpoints from user service docs #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b8adc7c
feat(user): add user services endpoints from user service docs
vrajpatelll e9e68b7
Fix test errors and address deprecation warnings
Devasy 8295706
Fix: Resolve Unprocessable Entity error in Swagger UI authorization (…
Devasy c911b84
fix(user): handle invalid ObjectId gracefully in user service methods
Devasy 54616a1
fix(user): correct key name for avatar in user document transformation
Devasy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| from fastapi import APIRouter, Depends, HTTPException, status | ||
| from app.user.schemas import UserProfileResponse, UserProfileUpdateRequest, DeleteUserResponse | ||
| from app.user.service import user_service | ||
| from app.auth.security import get_current_user | ||
| from typing import Dict, Any | ||
|
|
||
| router = APIRouter(prefix="/users", tags=["User"]) | ||
|
|
||
| @router.get("/me", response_model=UserProfileResponse) | ||
| async def get_current_user_profile(current_user: Dict[str, Any] = Depends(get_current_user)): | ||
| user = await user_service.get_user_by_id(current_user["_id"]) | ||
| if not user: | ||
| raise HTTPException(status_code=404, detail="User not found") | ||
| return user | ||
|
|
||
| @router.patch("/me", response_model=Dict[str, Any]) | ||
| async def update_user_profile( | ||
| updates: UserProfileUpdateRequest, | ||
| current_user: Dict[str, Any] = Depends(get_current_user) | ||
| ): | ||
| update_data = updates.model_dump(exclude_unset=True) | ||
| if not update_data: | ||
| raise HTTPException(status_code=400, detail="No update fields provided.") | ||
| updated_user = await user_service.update_user_profile(current_user["_id"], update_data) | ||
| if not updated_user: | ||
| raise HTTPException(status_code=404, detail="User not found") | ||
| return {"user": updated_user} | ||
|
|
||
| @router.delete("/me", response_model=DeleteUserResponse) | ||
| async def delete_user_account(current_user: Dict[str, Any] = Depends(get_current_user)): | ||
| deleted = await user_service.delete_user(current_user["_id"]) | ||
| if not deleted: | ||
| raise HTTPException(status_code=404, detail="User not found") | ||
| return DeleteUserResponse(success=True, message="User account scheduled for deletion.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| from pydantic import BaseModel, EmailStr, Field | ||
| from typing import Optional | ||
| from datetime import datetime | ||
|
|
||
| class UserProfileResponse(BaseModel): | ||
| id: str = Field(alias="_id") | ||
| name: str | ||
| email: EmailStr | ||
| imageUrl: Optional[str] = Field(default=None, alias="avatar") | ||
| currency: str = "USD" | ||
| createdAt: datetime | ||
| updatedAt: datetime | ||
|
|
||
| model_config = {"populate_by_name": True} | ||
|
|
||
| class UserProfileUpdateRequest(BaseModel): | ||
| name: Optional[str] = None | ||
| imageUrl: Optional[str] = None | ||
| currency: Optional[str] = None | ||
|
|
||
| class DeleteUserResponse(BaseModel): | ||
| success: bool = True | ||
| message: Optional[str] = None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| from fastapi import HTTPException, status, Depends | ||
| from app.database import get_database | ||
| from bson import ObjectId | ||
| from datetime import datetime, timezone | ||
| from typing import Optional, Dict, Any | ||
|
|
||
| class UserService: | ||
| def __init__(self): | ||
| pass | ||
|
|
||
| def get_db(self): | ||
| return get_database() | ||
|
|
||
| def transform_user_document(self, user: dict) -> dict: | ||
| if not user: | ||
| return None | ||
| try: | ||
| user_id = str(user["_id"]) | ||
| except Exception: | ||
| return None # Handle invalid ObjectId gracefully | ||
| return { | ||
| "_id": user_id, | ||
| "name": user.get("name"), | ||
| "email": user.get("email"), | ||
| "avatar": user.get("imageUrl") or user.get("avatar"), | ||
| "currency": user.get("currency", "USD"), | ||
| "createdAt": user.get("created_at"), | ||
| "updatedAt": user.get("updated_at") or user.get("created_at"), | ||
| } | ||
|
|
||
| async def get_user_by_id(self, user_id: str) -> Optional[dict]: | ||
| db = self.get_db() | ||
| try: | ||
| obj_id = ObjectId(user_id) | ||
| except Exception: | ||
| return None # Handle invalid ObjectId gracefully | ||
| user = await db.users.find_one({"_id": obj_id}) | ||
| return self.transform_user_document(user) | ||
|
|
||
| async def update_user_profile(self, user_id: str, updates: dict) -> Optional[dict]: | ||
| db = self.get_db() | ||
| try: | ||
| obj_id = ObjectId(user_id) | ||
| except Exception: | ||
| return None # Handle invalid ObjectId gracefully | ||
| updates["updated_at"] = datetime.now(timezone.utc) | ||
| result = await db.users.find_one_and_update( | ||
| {"_id": obj_id}, | ||
| {"$set": updates}, | ||
| return_document=True | ||
| ) | ||
| return self.transform_user_document(result) | ||
|
|
||
| async def delete_user(self, user_id: str) -> bool: | ||
| db = self.get_db() | ||
| try: | ||
| obj_id = ObjectId(user_id) | ||
| except Exception: | ||
| return False # Handle invalid ObjectId gracefully | ||
| result = await db.users.delete_one({"_id": obj_id}) | ||
| return result.deleted_count == 1 | ||
|
|
||
| user_service = UserService() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,3 +17,4 @@ httpx | |
| mongomock-motor | ||
| pytest-env | ||
| pytest-cov | ||
| pytest-mock | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.