topicsByAuthor fix

This commit is contained in:
tonyrewin 2022-09-07 19:19:13 +03:00
parent 365c2f25e7
commit e38d478ef2

View File

@ -1,13 +1,12 @@
from orm.topic import Topic, TopicFollower
from services.zine.topics import TopicStorage
from orm.shout import Shout
from orm.user import User
from services.stat.topicstat import TopicStat
from base.orm import local_session
from base.resolvers import mutation, query
from auth.authenticate import login_required
from sqlalchemy import and_
import random
from services.zine.shoutscache import ShoutsCache
@query.field("topicsAll")
@ -27,49 +26,45 @@ async def topics_by_community(_, info, community):
@query.field("topicsByAuthor")
async def topics_by_author(_, info, author):
slugs = set()
with local_session() as session:
shouts = session.query(Shout).filter(Shout.authors.any(User.slug == author))
for shout in shouts:
slugs.update([topic.slug for topic in shout.topics])
return await TopicStorage.get_topics(slugs)
async def topics_by_author(_, _info, author):
topics = await ShoutsCache.get_shouts_by_author(author)
author_topics = set()
for tpc in topics:
tpc = await TopicStorage.topics[tpc.slug]
tpc.stat = await TopicStat.get_stat(tpc.slug)
author_topics.add(tpc)
return list(author_topics)
@mutation.field("createTopic")
@login_required
async def create_topic(_, info, input):
new_topic = Topic.create(**input)
await TopicStorage.add_topic(new_topic)
async def create_topic(_, _info, inp):
new_topic = Topic.create(**inp)
await TopicStorage.update_topic(new_topic)
return {"topic": new_topic}
@mutation.field("updateTopic")
@login_required
async def update_topic(_, info, input):
slug = input["slug"]
async def update_topic(_, _info, inp):
slug = inp["slug"]
session = local_session()
topic = session.query(Topic).filter(Topic.slug == slug).first()
if not topic:
return {"error": "topic not found"}
topic.update(input)
topic.update(**inp)
session.commit()
session.close()
await TopicStorage.add_topic(topic)
await TopicStorage.update_topic(topic.slug)
return {"topic": topic}
def topic_follow(user, slug):
async def topic_follow(user, slug):
TopicFollower.create(follower=user.slug, topic=slug)
await TopicStorage.update_topic(slug)
def topic_unfollow(user, slug):
async def topic_unfollow(user, slug):
with local_session() as session:
sub = (
session.query(TopicFollower)
@ -80,8 +75,10 @@ def topic_unfollow(user, slug):
)
if not sub:
raise Exception("[resolvers.topics] follower not exist")
session.delete(sub)
else:
session.delete(sub)
session.commit()
await TopicStorage.update_topic(slug)
@query.field("topicsRandom")
@ -93,4 +90,5 @@ async def topics_random(_, info, amount=12):
topic.stat = topic_stat
if topic_stat["shouts"] > 2:
normalized_topics.push(topic)
return random.sample(normalized_topics, k=min(len(normalized_topics), 12))
sample_length = min(len(normalized_topics), amount)
return random.sample(normalized_topics, sample_length)