test_api/test_api/services/user.py

80 lines
2.5 KiB
Python

from uuid import UUID
from passlib.context import CryptContext
from sqlalchemy.exc import IntegrityError
from ..schemas.user_schema import UserDBDTO, UserWriteDTO
from ..uow.uow_base import UnitOfWork
class UserService:
def __init__(self, uow: UnitOfWork):
self.uow = uow
self.crypto_context = CryptContext(schemes="bcrypt")
async def get_all_users(self):
async with self.uow:
try:
res = await self.uow.users.find_all()
except IntegrityError as e:
await self.uow.rollback()
res = e._message()
else:
await self.uow.commit()
finally:
return res
async def add_one(self, data: UserWriteDTO):
new_data = data.model_dump()
new_data["hashed_password"] = self.crypto_context.hash(new_data.pop("password"))
dataf: UserDBDTO = UserDBDTO(**new_data)
async with self.uow:
try:
res = await self.uow.users.add_one(data=dataf)
except IntegrityError as e:
await self.uow.rollback()
res = e._message()
else:
await self.uow.commit()
finally:
return res
async def get_user(self, id: UUID):
async with self.uow:
try:
res = await self.uow.users.find_one(filter={"id": id})
except IntegrityError as e:
await self.uow.rollback()
res = e._message()
finally:
return res
async def patch_one(self, id: UUID, data: UserWriteDTO):
new_data = data.model_dump()
new_data["hashed_password"] = self.crypto_context.hash(new_data.pop("password"))
dataf = UserDBDTO(**new_data)
async with self.uow:
try:
res = await self.uow.users.patch_one(filter={"id": id}, data=dataf)
except IntegrityError as e:
await self.uow.rollback()
res = e._message()
else:
await self.uow.commit()
finally:
return res
async def delete_user(self, id: UUID) -> None | str:
async with self.uow:
try:
res = await self.uow.users.delete_one(filter={"id": id})
except IntegrityError as e:
await self.uow.rollback()
res = e._message()
else:
await self.uow.commit()
finally:
return res