core/resolvers/topics.py

76 lines
2.1 KiB
Python
Raw Normal View History

from orm.topic import Topic, TopicFollower
2022-08-11 09:09:57 +00:00
from services.zine.topics import TopicStorage
from orm.shout import Shout
from orm.user import User
2022-08-11 09:09:57 +00:00
from services.stat.topicstat import TopicStat
2022-08-11 05:53:14 +00:00
from base.orm import local_session
from base.resolvers import mutation, query
2021-10-28 10:42:34 +00:00
from auth.authenticate import login_required
from sqlalchemy import and_
2022-01-30 08:50:29 +00:00
2022-07-10 18:52:57 +00:00
@query.field("topicsAll")
2022-08-30 06:42:51 +00:00
async def topics_all(_, info, page = 1, size = 50):
topics = await TopicStorage.get_topics_all(page, size)
2022-08-12 12:50:59 +00:00
for topic in topics:
topic.stat = await TopicStat.get_stat(topic.slug)
2021-12-13 16:51:01 +00:00
return topics
2021-10-28 10:42:34 +00:00
@query.field("topicsByCommunity")
async def topics_by_community(_, info, community):
topics = await TopicStorage.get_topics_by_community(community)
2022-08-12 12:50:59 +00:00
for topic in topics:
topic.stat = await TopicStat.get_stat(topic.slug)
2022-07-13 15:53:06 +00:00
return topics
2021-10-28 10:42:34 +00:00
@query.field("topicsByAuthor")
async def topics_by_author(_, info, author):
2021-12-12 13:00:38 +00:00
slugs = set()
2021-10-28 10:42:34 +00:00
with local_session() as session:
2021-12-11 12:17:59 +00:00
shouts = session.query(Shout).\
filter(Shout.authors.any(User.slug == author))
for shout in shouts:
2021-12-12 13:00:38 +00:00
slugs.update([topic.slug for topic in shout.topics])
return await TopicStorage.get_topics(slugs)
2021-10-28 10:42:34 +00:00
@mutation.field("createTopic")
@login_required
async def create_topic(_, info, input):
new_topic = Topic.create(**input)
await TopicStorage.add_topic(new_topic)
return { "topic" : new_topic }
@mutation.field("updateTopic")
@login_required
async def update_topic(_, info, input):
slug = input["slug"]
session = local_session()
topic = session.query(Topic).filter(Topic.slug == slug).first()
if not topic:
return { "error" : "topic not found" }
topic.update(input)
session.commit()
session.close()
await TopicStorage.add_topic(topic)
return { "topic" : topic }
def topic_follow(user, slug):
TopicFollower.create(
follower = user.slug,
2022-01-30 08:50:29 +00:00
topic = slug)
def topic_unfollow(user, slug):
2021-10-28 10:42:34 +00:00
with local_session() as session:
sub = session.query(TopicFollower).\
filter(and_(TopicFollower.follower == user.slug, TopicFollower.topic == slug)).\
2022-01-30 08:50:29 +00:00
first()
if not sub:
raise Exception("[resolvers.topics] follower not exist")
2021-10-28 10:42:34 +00:00
session.delete(sub)
2022-01-30 08:50:29 +00:00
session.commit()