From 960a00101c9e0daddcaa0b324abb1ad7d59a1e65 Mon Sep 17 00:00:00 2001 From: Untone Date: Fri, 26 Jul 2024 19:04:40 +0300 Subject: [PATCH] load-comment-ratings --- resolvers/reaction.py | 49 +++++++++++++++++++++++++++++++++++++++++++ schema/query.graphql | 2 +- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/resolvers/reaction.py b/resolvers/reaction.py index 88bf09e7..714fe9fa 100644 --- a/resolvers/reaction.py +++ b/resolvers/reaction.py @@ -605,3 +605,52 @@ async def load_shout_comments(_, info, shout: int, limit=50, offset=0): reactions.add(reaction) return list(reactions) + +@query.field("load_comment_ratings") +async def load_comment_ratings(_, info, comment: int, limit=50, offset=0): + + """ + getting paginated comments with stats + :param info: graphql meta + :param comment: int replied comment id + :param limit: int amount of reactions + :param offset: int offset in this order + :return: Reaction[] + """ + aliased_reaction = aliased(Reaction) + q = ( + select( + Reaction, + Author, + Shout, + func.count(aliased_reaction.id).label("reacted_stat"), + func.count(aliased_reaction.body).label("commented_stat"), + func.sum(func.coalesce(aliased_reaction.likes, 0)).label("likes_stat"), + func.sum(func.coalesce(aliased_reaction.dislikes, 0)).label("dislikes_stat"), + ) + .select_from(Reaction) + .join(Author, Reaction.created_by == Author.id) + .join(Shout, Reaction.shout == Shout.id) + ) + + # filter, group, order, limit, offset + q = q.filter(and_(Reaction.deleted_at.is_(None), Reaction.reply_to == comment, Reaction.body.is_not(None))) + q = q.group_by(Reaction.id, Author.id, Shout.id) + q = q.order_by(desc(Reaction.created_at)) + q = q.limit(limit).offset(offset) + + reactions = set() + with local_session() as session: + result_rows = session.execute(q) + for row in result_rows: + reaction, author, shout, reacted_stat, commented_stat, likes_stat, dislikes_stat = row + reaction.created_by = author + reaction.shout = shout + reaction.stat = { + "rating": int(likes_stat or 0) - int(dislikes_stat or 0), + "reacted": reacted_stat, + "commented": commented_stat, + } + reactions.add(reaction) + + return list(reactions) diff --git a/schema/query.graphql b/schema/query.graphql index 7a6bf278..87511d02 100644 --- a/schema/query.graphql +++ b/schema/query.graphql @@ -29,7 +29,7 @@ type Query { load_shouts_by(options: LoadShoutsOptions): [Shout] load_shout_comments(shout: Int!, limit: Int, offset: Int): [Reaction] load_shout_ratings(shout: Int!, limit: Int, offset: Int): [Reaction] - load_comment_ratings(shout: Int!, limit: Int, offset: Int): [Reaction] + load_comment_ratings(comment: Int!, limit: Int, offset: Int): [Reaction] load_shouts_search(text: String!, limit: Int, offset: Int): [SearchResult] load_shouts_feed(options: LoadShoutsOptions): [Shout] load_shouts_unrated(limit: Int, offset: Int): [Shout]