From 56db33d7f18ec888ead111234d20e8de56786598 Mon Sep 17 00:00:00 2001 From: Untone Date: Tue, 4 Feb 2025 02:53:01 +0300 Subject: [PATCH] get_my_rates_comments-fix --- CHANGELOG.md | 2 ++ cache/cache.py | 10 ++++++---- cache/triggers.py | 34 +++++++++++++++++----------------- resolvers/editor.py | 38 +++++++++++++++++++------------------- resolvers/rating.py | 12 +++++++++++- resolvers/reader.py | 2 +- resolvers/stat.py | 4 ++-- 7 files changed, 58 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48bd1800..085241e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ - `Reaction.deleted_at` filter on `update_reaction` resolver added - `triggers` module updated with `after_shout_handler`, `after_reaction_handler` for cache revalidation - `after_shout_handler`, `after_reaction_handler` now also handle `deleted_at` field +- `get_cached_topic_followers` fixed +- `get_my_rates_comments` fixed #### [0.4.7] - `get_my_rates_shouts` resolver added with: diff --git a/cache/cache.py b/cache/cache.py index 8c286d0d..b962a534 100644 --- a/cache/cache.py +++ b/cache/cache.py @@ -160,7 +160,7 @@ async def get_cached_topic_followers(topic_id: int): Args: topic_id: Идентификатор темы, подписчиков которой необходимо получить. - + Returns: List[dict]: Список подписчиков темы, каждый элемент представляет собой словарь с данными автора. """ @@ -175,10 +175,12 @@ async def get_cached_topic_followers(topic_id: int): # Если данные не найдены в кеше, загрузка из базы данных with local_session() as session: - result = session.query(Author.id)\ - .join(TopicFollower, TopicFollower.follower == Author.id)\ - .filter(TopicFollower.topic == topic_id)\ + result = ( + session.query(Author.id) + .join(TopicFollower, TopicFollower.follower == Author.id) + .filter(TopicFollower.topic == topic_id) .all() + ) followers_ids = [f[0] for f in result] # Кэширование результатов diff --git a/cache/triggers.py b/cache/triggers.py index 0b1ea35b..e8b20ef7 100644 --- a/cache/triggers.py +++ b/cache/triggers.py @@ -5,8 +5,8 @@ from orm.author import Author, AuthorFollower from orm.reaction import Reaction, ReactionKind from orm.shout import Shout, ShoutAuthor, ShoutReactionsFollower from orm.topic import Topic, TopicFollower -from utils.logger import root_logger as logger from services.db import local_session +from utils.logger import root_logger as logger def mark_for_revalidation(entity, *args): @@ -48,17 +48,17 @@ def after_shout_handler(mapper, connection, target): """Обработчик изменения статуса публикации""" if not isinstance(target, Shout): return - + # Проверяем изменение статуса публикации was_published = target.published_at is not None and target.deleted_at is None - + # Всегда обновляем счетчики для авторов и тем при любом изменении поста for author in target.authors: revalidation_manager.mark_for_revalidation(author.id, "authors") - + for topic in target.topics: revalidation_manager.mark_for_revalidation(topic.id, "topics") - + # Обновляем сам пост revalidation_manager.mark_for_revalidation(target.id, "shouts") @@ -67,35 +67,35 @@ def after_reaction_handler(mapper, connection, target): """Обработчик для комментариев""" if not isinstance(target, Reaction): return - + # Проверяем что это комментарий is_comment = target.kind == ReactionKind.COMMENT.value - + # Получаем связанный пост shout_id = target.shout if isinstance(target.shout, int) else target.shout.id if not shout_id: return - + # Обновляем счетчики для автора комментария if target.created_by: revalidation_manager.mark_for_revalidation(target.created_by, "authors") - + # Обновляем счетчики для поста revalidation_manager.mark_for_revalidation(shout_id, "shouts") - + if is_comment: # Для комментариев обновляем также авторов и темы with local_session() as session: - shout = session.query(Shout).filter( - Shout.id == shout_id, - Shout.published_at.is_not(None), - Shout.deleted_at.is_(None) - ).first() - + shout = ( + session.query(Shout) + .filter(Shout.id == shout_id, Shout.published_at.is_not(None), Shout.deleted_at.is_(None)) + .first() + ) + if shout: for author in shout.authors: revalidation_manager.mark_for_revalidation(author.id, "authors") - + for topic in shout.topics: revalidation_manager.mark_for_revalidation(topic.id, "topics") diff --git a/resolvers/editor.py b/resolvers/editor.py index bb64a441..8d5b44e1 100644 --- a/resolvers/editor.py +++ b/resolvers/editor.py @@ -468,28 +468,28 @@ async def update_shout(_, info, shout_id: int, shout_input=None, publish=False): .filter(Shout.id == shout_id) .first() ) - + # Создаем словарь с базовыми полями shout_dict = shout_with_relations.dict() - + # Явно добавляем связанные данные - shout_dict["topics"] = [ - { - "id": topic.id, - "slug": topic.slug, - "title": topic.title - } - for topic in shout_with_relations.topics - ] if shout_with_relations.topics else [] - - shout_dict["authors"] = [ - { - "id": author.id, - "name": author.name, - "slug": author.slug - } - for author in shout_with_relations.authors - ] if shout_with_relations.authors else [] + shout_dict["topics"] = ( + [ + {"id": topic.id, "slug": topic.slug, "title": topic.title} + for topic in shout_with_relations.topics + ] + if shout_with_relations.topics + else [] + ) + + shout_dict["authors"] = ( + [ + {"id": author.id, "name": author.name, "slug": author.slug} + for author in shout_with_relations.authors + ] + if shout_with_relations.authors + else [] + ) logger.info(f"Final shout data with relations: {shout_dict}") return {"shout": shout_dict, "error": None} diff --git a/resolvers/rating.py b/resolvers/rating.py index 216d20e1..23a2acd4 100644 --- a/resolvers/rating.py +++ b/resolvers/rating.py @@ -15,11 +15,21 @@ from utils.logger import root_logger as logger async def get_my_rates_comments(_, info, comments: list[int]) -> list[dict]: """ Получение реакций пользователя на комментарии + + Args: + info: Контекст запроса + comments: Список ID комментариев + + Returns: + list[dict]: Список словарей с реакциями пользователя на комментарии + Каждый словарь содержит: + - comment_id: ID комментария + - my_rate: Тип реакции (LIKE/DISLIKE) """ author_dict = info.context.get("author") if info.context else None author_id = author_dict.get("id") if author_dict else None if not author_id: - return {"error": "Author not found"} + return [] # Возвращаем пустой список вместо словаря с ошибкой # Подзапрос для реакций текущего пользователя rated_query = ( diff --git a/resolvers/reader.py b/resolvers/reader.py index 4ce97266..a99ccfd1 100644 --- a/resolvers/reader.py +++ b/resolvers/reader.py @@ -69,7 +69,7 @@ def query_with_stat(info): Shout.deleted_at.is_(None), # Проверяем deleted_at ) ) - + # Главный автор main_author = aliased(Author) q = q.join(main_author, main_author.id == Shout.created_by) diff --git a/resolvers/stat.py b/resolvers/stat.py index d149aef1..37de7dc7 100644 --- a/resolvers/stat.py +++ b/resolvers/stat.py @@ -113,7 +113,7 @@ def get_topic_shouts_stat(topic_id: int) -> int: ) ) ) - + with local_session() as session: result = session.execute(q).first() return result[0] if result else 0 @@ -208,7 +208,7 @@ def get_author_shouts_stat(author_id: int) -> int: and_( aliased_shout_author.author == author_id, aliased_shout.published_at.is_not(None), - aliased_shout.deleted_at.is_(None) # Добавляем проверку на удаление + aliased_shout.deleted_at.is_(None), # Добавляем проверку на удаление ) ) )