core/resolvers/community.py

72 lines
2.3 KiB
Python
Raw Normal View History

2024-01-25 19:41:27 +00:00
from sqlalchemy import and_, distinct, func, select
2023-12-17 20:30:20 +00:00
2023-10-23 14:47:11 +00:00
from orm.author import Author
from orm.community import Community, CommunityAuthor
from orm.shout import ShoutCommunity
2023-12-17 20:30:20 +00:00
from services.db import local_session
2024-02-20 16:19:46 +00:00
from services.logger import root_logger as logger
2024-04-08 07:38:58 +00:00
from services.schema import query
2024-01-25 19:41:27 +00:00
2023-10-23 14:47:11 +00:00
def get_communities_from_query(q):
ccc = []
with local_session() as session:
2024-01-23 02:03:23 +00:00
for [c, shouts_stat, followers_stat] in session.execute(q):
2023-10-23 14:47:11 +00:00
c.stat = {
2024-04-23 12:14:59 +00:00
"shouts": session.execute(
2024-05-30 04:12:00 +00:00
select(func.count(distinct(ShoutCommunity.shout))).filter(ShoutCommunity.community == c.id)
2024-04-23 12:14:59 +00:00
),
# "authors": session.execute(select(func.count(distinct(ShoutCommunity.shout))).filter(ShoutCommunity.community == c.id)),
# "followers": session.execute(select(func.count(distinct(ShoutCommunity.shout))).filter(ShoutCommunity.community == c.id)),
2024-01-23 02:03:23 +00:00
# "commented": commented_stat,
2023-10-23 14:47:11 +00:00
}
ccc.append(c)
return ccc
# for mutation.field("follow")
2023-10-05 22:02:14 +00:00
def community_follow(follower_id, slug):
2023-10-23 14:47:11 +00:00
try:
with local_session() as session:
2024-01-23 18:34:51 +00:00
community = session.query(Community).where(Community.slug == slug).first()
if isinstance(community, Community):
cf = CommunityAuthor(author=follower_id, community=community.id)
session.add(cf)
session.commit()
return True
2024-01-25 19:41:27 +00:00
except Exception as ex:
logger.debug(ex)
2024-01-23 18:34:51 +00:00
return False
2023-10-05 21:42:34 +00:00
2023-10-23 14:47:11 +00:00
# for mutation.field("unfollow")
2023-10-05 22:02:14 +00:00
def community_unfollow(follower_id, slug):
2023-10-23 14:47:11 +00:00
with local_session() as session:
flw = (
session.query(CommunityAuthor)
.join(Community, Community.id == CommunityAuthor.community)
.filter(and_(CommunityAuthor.author == follower_id, Community.slug == slug))
.first()
)
if flw:
session.delete(flw)
session.commit()
return True
return False
2024-04-17 15:32:23 +00:00
@query.field("get_communities_all")
2023-10-23 14:47:11 +00:00
async def get_communities_all(_, _info):
q = select(Author)
return get_communities_from_query(q)
2024-04-17 15:32:23 +00:00
@query.field("get_community")
2024-02-24 10:22:35 +00:00
async def get_community(_, _info, slug: str):
2023-10-23 14:47:11 +00:00
q = select(Community).where(Community.slug == slug)
2023-11-30 08:40:27 +00:00
communities = get_communities_from_query(q)
return communities[0]