from fastapi import Body, Request, HTTPException, status from fastapi.encoders import jsonable_encoder import sys from ..models.users import User, UpdateUser from bson import ObjectId import re def create_user(collection, user: User = Body(...)): user = jsonable_encoder(user) new_user = collection.insert_one(user) created_user = collection.find_one({"_id": new_user.inserted_id}) print("NEW ID IS:.........", new_user.inserted_id) return created_user def list_users(collection, limit: int): try: users = list(collection.find(limit = limit)) return users except: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No users found!") def find_user(collection, user_id: str): if (user := collection.find_one({"user_id": user_id})): return user else: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User with user_id {user_id} not found!") def find_name_from_id(collection, user_id: str): # find_one user record based on user id and project for user name if (user_name := collection.find_one({"user_id": user_id}, {"name": 1, "_id": 0})): return user_name['name'] # index name field from single field record returned else: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User with user_id {user_id} not found!") def find_user_name(collection, name: str): # search for name in lowercase if (user := collection.find_one({"name": re.compile('^' + re.escape(name) + '$', re.IGNORECASE)})): return user else: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User with name {name} not found!") def find_user_email(collection, email: str): if (user := collection.find_one({"email": re.compile('^' + re.escape(email) + '$', re.IGNORECASE)})): return user else: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User with Email Address {email} not found!") ''' Update user record based on user object/json''' def update_user(collection, user_id: str, user: UpdateUser): try: user = {k: v for k, v in user.model_dump().items() if v is not None} if len(user) >= 1: update_result = collection.update_one({"user_id": user_id}, {"$set": user}) if update_result.modified_count == 0: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User with user_id: '{user_id}' not found and updated!") if (existing_users := collection.find_one({"user_id": user_id})) is not None: return existing_users except: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User with user_id: '{user_id}' not found and updated!") def delete_user(collection, user_id: str): try: deleted_user = collection.delete_one({"user_id": user_id}) if deleted_user.deleted_count == 1: return f"User with user_id {user_id} deleted sucessfully" except: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User with user_id {user_id} not found!")