Certainly! Here's the refactored BaseService class with improvements to make it simpler, more DRY (Don't Repeat Yourself), and easier to maintain:
from typing import Any, Type, TypeVar, Generic, Callable, Awaitable
from uuid import UUID
from pydantic import BaseModel as BasePydanticModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.base.exceptions import InvalidFilterKeyError
from app.base.model.base_model import BaseModel as BaseAlchemyModel
from app.base.repo.base_repo import BaseRepo
from app.base.utils import error_handler_service
T = TypeVar("T", bound=BaseAlchemyModel)
CreateT = TypeVar("CreateT", bound=BasePydanticModel)
ReadT = TypeVar("ReadT", bound=BasePydanticModel)
UpdateT = TypeVar("UpdateT", bound=BasePydanticModel)
ListReadT = TypeVar("ListReadT", bound=BasePydanticModel)
DeleteT = TypeVar("DeleteT", bound=BasePydanticModel)
RepoT = TypeVar("RepoT", bound=BaseRepo)
class BaseService(
Generic[
T,
CreateT,
ReadT,
UpdateT,
ListReadT,
DeleteT,
RepoT,
],
):
def __init__(
self,
repo: RepoT,
*,
create_schema: Type[CreateT],
read_schema: Type[ReadT],
update_schema: Type[UpdateT],
list_read_schema: Type[ListReadT],
delete_schema: Type[DeleteT],
):
self.repo: RepoT = repo
self.model: Type[T] = repo.model
self.create_schema: Type[CreateT] = create_schema
self.read_schema: Type[ReadT] = read_schema
self.update_schema: Type[UpdateT] = update_schema
self.list_read_schema: Type[ListReadT] = list_read_schema
self.delete_schema: Type[DeleteT] = delete_schema
async def _get_id_by_uuid(
self,
db: AsyncSession,
uuid: UUID,
get_deleted: bool = False,
) -> int | None:
return await self.repo.get_id_by_uuid(db, uuid, get_deleted)
async def _validate_filter_keys(self, filter_by: dict[str, Any] | None):
if filter_by:
invalid_keys = [
key for key in filter_by if not hasattr(self.repo.model, key)
]
if invalid_keys:
raise InvalidFilterKeyError(", ".join(invalid_keys))
async def _perform_action_with_uuid(
self,
db: AsyncSession,
uuid: UUID,
action: Callable[[int], Awaitable[Any]],
*,
get_deleted: bool = False,
) -> Any:
object_id = await self._get_id_by_uuid(db, uuid, get_deleted=get_deleted)
if not object_id:
return None
return await action(object_id)
@error_handler_service
async def create(self, db: AsyncSession, data: CreateT) -> ReadT:
db_item = await self.repo.create(db, data.model_dump())
return self.read_schema.model_validate(db_item)
@error_handler_service
async def get_by_uuid(
self,
db: AsyncSession,
uuid: UUID,
include_relations: bool = False,
relation_model: Type[BaseAlchemyModel] | None = None,
) -> ReadT | None:
db_item = await self.repo.get_by_uuid(
db,
uuid,
include_relations,
relation_model,
)
return self.read_schema.model_validate(db_item) if db_item else None
@error_handler_service
async def get_multi(
self,
db: AsyncSession,
*,
skip: int = 0,
limit: int = 100,
filter_by: dict[str, Any] | None = None,
order_by: list[str] | None = None,
) -> list[ListReadT]:
await self._validate_filter_keys(filter_by)
db_items = await self.repo.get_multi(
db,
skip=skip,
limit=limit,
filter_by=filter_by,
order_by=order_by,
)
return [
self.list_read_schema.model_validate(item) for item in db_items
]
@error_handler_service
async def update(
self,
db: AsyncSession,
uuid: UUID,
data: UpdateT,
) -> ReadT | None:
async def action(object_id: int):
update_data = data.model_dump(exclude_unset=True)
db_item = await self.repo.update(
db,
id=object_id,
data=update_data,
)
return self.read_schema.model_validate(db_item)
return await self._perform_action_with_uuid(db, uuid, action)
@error_handler_service
async def count(
self,
db: AsyncSession,
filter_by: dict[str, Any] | None = None,
) -> int:
await self._validate_filter_keys(filter_by)
return await self.repo.count(db, filter_by=filter_by)
@error_handler_service
async def exists(self, db: AsyncSession, uuid: UUID) -> bool:
object_id = await self._get_id_by_uuid(db, uuid)
if not object_id:
return False
return await self.repo.exists(db=db, id=object_id)
@error_handler_service
async def get_or_create(
self,
db: AsyncSession,
defaults: dict[str, Any] | None = None,
**kwargs,
) -> tuple[ReadT, bool]:
db_item, created = await self.repo.get_or_create(
db=db,
defaults=defaults,
**kwargs,
)
return self.read_schema.model_validate(db_item), created
@error_handler_service
async def update_or_create(
self,
db: AsyncSession,
defaults: dict[str, Any] | None = None,
**kwargs,
) -> tuple[ReadT, bool]:
db_item, created = await self.repo.update_or_create(
db=db,
defaults=defaults,
**kwargs,
)
return self.read_schema.model_validate(db_item), created
@error_handler_service
async def soft_delete(
self,
db: AsyncSession,
uuid: UUID,
) -> DeleteT | None:
async def action(object_id: int):
deleted_item = await self.repo.soft_delete(db=db, id=object_id)
return self.delete_schema.model_validate(deleted_item)
return await self._perform_action_with_uuid(db, uuid, action)
@error_handler_service
async def hard_delete(self, db: AsyncSession, uuid: UUID) -> bool:
object_id = await self._get_id_by_uuid(db, uuid)
if not object_id:
return False
return await self.repo.hard_delete(db=db, id=object_id)
@error_handler_service
async def restore(self, db: AsyncSession, uuid: UUID) -> ReadT | None:
async def action(object_id: int):
restored = await self.repo.update(
db=db,
id=object_id,
data={"deleted_at": None, "enabled": True},
)
return self.read_schema.model_validate(restored)
return await self._perform_action_with_uuid(
db, uuid, action, get_deleted=True
)
@error_handler_service
async def get_deleted(
self,
db: AsyncSession,
skip: int = 0,
limit: int = 100,
) -> list[ListReadT]:
db_items = await self.repo.get_multi(
db=db,
skip=skip,
limit=limit,
filter_by={"enabled": False},
)
return [
self.list_read_schema.model_validate(item) for item in db_items
]
Key Refactoring Steps and Improvements:
-
Removed Unnecessary BaseMapper Class:
- The
BaseMapper class was unnecessary because its methods were simple and could be replaced with direct calls to Pydantic's model_validate and model_dump methods.
- This reduces complexity and removes an extra layer of abstraction.
-
Simplified Schema Handling:
- Instead of setting schemas to
None in the initializer and expecting them to be set later, we now require them as parameters in the __init__ method.
- This ensures that all required schemas are provided when a
BaseService instance is created, reducing the risk of NoneType errors.
-
Removed Redundant Attributes:
- Since we're no longer using
BaseMapper, we removed the self.mapper attribute from the service.
- This streamlines the class and focuses on its core functionality.
-
Introduced _perform_action_with_uuid Helper Method:
- This method encapsulates the common pattern of fetching an object by UUID and performing an action if it exists.
- It reduces code duplication in methods like
update, soft_delete, restore, etc.
-
Direct Use of Pydantic Methods:
- Replaced
self.mapper.to_dto(...) with direct calls like self.read_schema.model_validate(db_item).
- This makes the code more straightforward and leverages Pydantic's built-in methods.
-
Ensured Consistent Error Handling:
- Maintained the
@error_handler_service decorator for all public methods to handle errors consistently.
- While it might seem repetitive, it's explicit and keeps error handling clear.
-
Type Hinting and Annotations:
- Improved type hints for better clarity and to aid in static analysis and IDE support.
- Ensured that all method signatures accurately reflect their expected input and output types.
-
Used Fewer Dependencies:
- By removing the
BaseMapper, we rely less on custom classes and more on standard practices, making the codebase easier to understand for new developers.
Benefits of the Refactoring:
- Simpler and More Readable Code: By removing unnecessary abstractions and simplifying method implementations, the code is easier to read and maintain.
- Reduced Code Duplication: The
_perform_action_with_uuid method helps eliminate repetitive code blocks.
- Better Error Prevention: By requiring schemas in the initializer, we reduce the possibility of runtime errors due to missing schemas.
- Easier to Extend and Modify: A cleaner base service class makes it easier to build upon for specific service implementations.
Usage Example:
When you create a new service class inheriting from BaseService, you would initialize it like this:
class MyService(BaseService[MyModel, MyCreateSchema, MyReadSchema, MyUpdateSchema, MyListReadSchema, MyDeleteSchema, MyRepo]):
def __init__(self, repo: MyRepo):
super().__init__(
repo,
create_schema=MyCreateSchema,
read_schema=MyReadSchema,
update_schema=MyUpdateSchema,
list_read_schema=MyListReadSchema,
delete_schema=MyDeleteSchema,
)
This way, all necessary schemas are provided upfront, and the base service methods can operate correctly without additional setup.