diff --git a/resolvers/reader.py b/resolvers/reader.py index 958358b7..7caf5b13 100644 --- a/resolvers/reader.py +++ b/resolvers/reader.py @@ -8,7 +8,7 @@ from orm.reaction import Reaction, ReactionKind from orm.shout import Shout, ShoutAuthor, ShoutTopic from orm.topic import Topic, TopicFollower from resolvers.reaction import add_reaction_stat_columns -from resolvers.topic import random_topic_query +from resolvers.topic import get_topics_random from services.auth import login_required from services.db import local_session from services.schema import query @@ -461,32 +461,36 @@ async def load_shouts_random_top(_, _info, options): @query.field('load_shouts_random_topic') async def load_shouts_random_topic(_, info, limit: int = 10): - random_topic_subquery = random_topic_query(1).subquery() + [topic] = get_topics_random(None, None, 1) + if topic: + shouts = fetch_shouts_by_topic(topic, limit) + if shouts: + return {'topic': topic, 'shouts': shouts} + return { + 'error': 'failed to get random topic after few retries', + 'shouts': [], + 'topic': {}, + } + + +def fetch_shouts_by_topic(topic, limit): q = ( - select(Topic, Shout) - .select_from(Topic) - .join(Shout, Shout.topics.any(Topic.id == random_topic_subquery.c.id)) - .options(joinedload(Shout.authors)) + select(Shout) + .options(joinedload(Shout.authors), joinedload(Shout.topics)) .filter( and_( Shout.deleted_at.is_(None), Shout.featured_at.is_not(None), - Shout.topics.any(slug=Topic.slug), + Shout.topics.any(slug=topic.slug), ) ) ) aliased_reaction = aliased(Reaction) q = add_reaction_stat_columns(q, aliased_reaction) - q = q.group_by(Shout.id, Topic.slug).order_by(desc(Shout.created_at)).limit(limit) - result = local_session().execute(q) - if result: - topic, shouts = result[0] - return {'topic': topic, 'shouts': shouts} + q = q.group_by(Shout.id).order_by(desc(Shout.created_at)).limit(limit) - return { - 'error': 'failed to get random topic after few retries', - 'shouts': [], - 'topic': None - } + shouts = get_shouts_from_query(q) + + return shouts diff --git a/resolvers/topic.py b/resolvers/topic.py index 64ce81da..5f87ccfa 100644 --- a/resolvers/topic.py +++ b/resolvers/topic.py @@ -122,7 +122,11 @@ def topic_unfollow(follower_id, slug): @query.field('get_topics_random') def get_topics_random(_, _info, amount=12): - q = random_topic_query(amount) + q = select(Topic) + q = q.join(ShoutTopic) + q = q.group_by(Topic.id) + q = q.having(func.count(distinct(ShoutTopic.shout)) > 2) + q = q.order_by(func.random()).limit(amount) topics = [] with local_session() as session: @@ -130,12 +134,3 @@ def get_topics_random(_, _info, amount=12): topics.append(topic) return topics - - -def random_topic_query(amount: int): - q = select(Topic) - q = q.join(ShoutTopic) - q = q.group_by(Topic.id) - q = q.having(func.count(distinct(ShoutTopic.shout)) > 2) - q = q.order_by(func.random()).limit(amount) - return q