language-learning-app/api/app/domain/services/article_service.py

74 lines
2.2 KiB
Python
Raw Permalink Normal View History

import logging
from uuid import UUID, uuid4
from app.domain.models.article import Article, ArticleOwnershipRoleEnum, ArticleTypeEnum
from app.outbound.postgres.repositories.article_repository import (
ArticleOwnershipRepository,
ArticleRepository,
)
logger = logging.getLogger(__name__)
class ArticleService:
def __init__(
self,
article_repository: ArticleRepository,
article_ownership_repository: ArticleOwnershipRepository,
) -> None:
self.article_repository = article_repository
self.article_ownership_repository = article_ownership_repository
return
async def create_article_as_user(
self,
article_type: ArticleTypeEnum,
language: str,
target_complexity: str,
title: str,
text: str,
user_id: str,
) -> Article:
article = await self.article_repository.create(
article_type=article_type,
language=language,
target_complexity=target_complexity,
title=title,
text=text,
)
await self.article_ownership_repository.create(
article_id=UUID(article.id),
ownership_role=ArticleOwnershipRoleEnum.owner,
user_id=UUID(user_id),
)
return article
async def get_articles_for_user(self, user_id: str) -> list[Article]:
articles = await self.article_repository.get_non_deleted_articles_for_owner(
UUID(user_id)
)
return articles
async def get_article_as_user(
self, article_id: str, user_id: str
) -> Article | None:
aid = UUID(article_id)
article = await self.article_repository.get_by_id(aid)
if article is None:
logger.info(f"Article with id {article_id} not found")
return None
ownerships = await self.article_ownership_repository.get_by_article_id(aid)
print(f"Current user: {user_id}")
for o in ownerships:
print(o)
if not any(ownership.user_id == user_id for ownership in ownerships):
logger.info(
f"User with id {user_id} does not have access to article with id {article_id}"
)
return None
return article