Skip to content

Get comment reaction#156

Open
tishanovartem wants to merge 7 commits intomainfrom
get_comment_reaction
Open

Get comment reaction#156
tishanovartem wants to merge 7 commits intomainfrom
get_comment_reaction

Conversation

@tishanovartem
Copy link

@tishanovartem tishanovartem commented Nov 12, 2025

Что сделано:

  • В ручке GET /comment/{uuid} теперь возвращаются флаги is_liked и is_disliked, которые показывают поставил ли текущий пользователь лайк/дизлайк на комментарий.
  • Реализован гибридный метод has_reaction() в модели Comment для эффективной проверки реакций пользователь.

Детали реализации

Check-List

  • Вы проверили свой код перед отправкой запроса?
  • Вы написали тесты к реализованным функциям?
  • Вы не забыли применить форматирование black и isort для Back-End или Prettier для Front-End?

@github-actions
Copy link

💩 Code linting failed, use black and isort to fix it.

@github-actions
Copy link

github-actions bot commented Nov 12, 2025

Code Coverage

Coverage Report
FileStmtsMissCoverMissing
rating_api
   __main__.py440%1–7
   exceptions.py43784%35–37, 48–50, 58
rating_api/models
   base.py64494%24–27
   db.py1641889%115, 117, 119, 121, 132, 171, 189, 199, 213, 222–224, 257, 271–283
rating_api/routes
   base.py16194%41
   comment.py1443576%64, 82, 131–132, 153–162, 172, 236–237, 239–240, 248–253, 262, 269–271, 295, 308, 335–346, 377
   exc_handlers.py32391%36, 43, 50
   lecturer.py109992%70–71, 81, 87–88, 217, 225, 243, 249
rating_api/schemas
   base.py12467%6–9
   models.py155398%189, 191, 201
rating_api/utils
   mark.py880%1–20
TOTAL7859688% 

Summary

Tests Skipped Failures Errors Time
88 0 💤 0 ❌ 0 🔥 25.487s ⏱️

Copy link
Member

@Zimovchik Zimovchik left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нужно и в ручке get comments тоже это сделать

Comment on lines +268 to +278
@classmethod
def reactions_for_comments(cls, user_id: int, session, comments):
if not user_id or not comments:
return {}
comments_uuid = [c.uuid for c in comments]
reactions = (
session.query(CommentReaction)
.filter(CommentReaction.user_id == user_id, CommentReaction.comment_uuid.in_(comments_uuid))
.all()
)
return {r.comment_uuid: r.reaction for r in reactions}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ты можешь сделать это методами алхимии, групнув сджойненые таблички например и посмотрев 1 0 или -1

@github-actions
Copy link

github-actions bot commented Mar 5, 2026

💩 Code linting failed, use black and isort to fix it.

@tishanovartem tishanovartem requested review from petrCher and removed request for MikhailPI1 March 5, 2026 18:36
@petrCher
Copy link
Member

petrCher commented Mar 7, 2026

Сейчас такая проблема: ты добавил новую схему CommentGetWithLike, наследующуяся от CommentGet. Сперва кажется что решение красивое, но появляется масса проблем при новое схеме. Ты не учел, например, что в ручках получения лекторов тоже есть вывод комментариев, который остался со старой логикой CommentGet. Также пришлось добавлять новые схемы, что неудобно. Не понял, кстати, зачем ты закомменченные схемы добавил? Если на будущее, то об этом лучше писать в чат бэкенда как идея на будущее.
Предлагаю сейчас просто добавить два новых булевых поля is_liked и is_disliked добавить в исходную схему CommentGet, тогда проблем не будет


@comment.get("", response_model=Union[CommentGetAll, CommentGetAllWithAllInfo, CommentGetAllWithStatus])
@comment.get(
"", response_model=Union[CommentGetAll, CommentGetAllWithLike, CommentGetAllWithAllInfo, CommentGetAllWithStatus]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

здесь надо привезти это к одной строке обратно

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну и плюс убрать лишнюю схему


`asc_order` -Если передано true, сортировать в порядке возрастания. Иначе - в порядке убывания
"""
user = {"id": 101, "session_scopes": []} # тестовый user_id # пустые скоупы = обычный пользователь
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:)
если это для тестов у тебя было, рекомендую убрать))



"""
class CommentGetWithLikeAndStatus(CommentGetWithLike):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем?
ты хочешь добавить ревью на лайки/дизлайки?) это точно не надо делать будет



"""
class CommentGetWithAllInfoAndLike(CommentGetWithLike):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

убрать

total: int


"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

убрать

total: int


"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

убрать

total: int


class CommentGetAllWithLike(Base):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

чувствуешь как усложнилась логика из-за добавления схемы CommentGetWithLike?

if reaction_data:
user_id, reaction_type = reaction_data
reaction = CommentReaction(user_id=user_id, comment_uuid=comment.uuid, reaction=reaction_type)
dbsession.add(reaction)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

все что связано с обращением к базе данных должно быть вынесено в conftest.py
Если есть вопросы как это делать напиши мне, помогу. А так можешь чекнуть аналогичные соседние тесты или в рентал апи зайти и посмотреть как там


result.total = len(result.comments)
result.comments = [comment_validator.model_validate(comment) for comment in result.comments]
comments_with_like = []
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

здесь пока логику не проверил, чекну как только исправишь что я написал

@tishanovartem tishanovartem force-pushed the get_comment_reaction branch from 3858a9d to 533a554 Compare March 9, 2026 19:52
@github-actions
Copy link

github-actions bot commented Mar 9, 2026

💩 Code linting failed, use black and isort to fix it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

в get_comment выводить для юзера, лайкнул ли он этот коммент

3 participants