core/resolvers/bookmark.py

84 lines
2.4 KiB
Python
Raw Normal View History

2024-11-01 06:50:19 +00:00
from operator import and_
2024-11-01 08:09:16 +00:00
2024-10-21 07:52:23 +00:00
from graphql import GraphQLError
2024-11-01 10:50:47 +00:00
from sqlalchemy import delete, insert
2024-10-21 07:52:23 +00:00
from orm.author import AuthorBookmark
from orm.shout import Shout
2024-11-01 06:50:19 +00:00
from resolvers.feed import apply_options
2024-11-01 10:50:47 +00:00
from resolvers.reader import get_shouts_with_links, query_with_stat
2024-11-01 06:50:19 +00:00
from services.auth import login_required
2024-10-21 07:52:23 +00:00
from services.common_result import CommonResult
from services.db import local_session
from services.schema import mutation, query
@query.field("load_shouts_bookmarked")
2024-11-01 06:50:19 +00:00
@login_required
def load_shouts_bookmarked(_, info, options):
2024-10-21 07:52:23 +00:00
"""
Load bookmarked shouts for the authenticated user.
Args:
limit (int): Maximum number of shouts to return.
offset (int): Number of shouts to skip.
Returns:
list: List of bookmarked shouts.
"""
author_dict = info.context.get("author", {})
author_id = author_dict.get("id")
if not author_id:
raise GraphQLError("User not authenticated")
2024-11-01 06:50:19 +00:00
2024-11-01 10:50:47 +00:00
q = query_with_stat(info)
2024-11-01 06:50:19 +00:00
q = q.join(AuthorBookmark)
q = q.filter(
2024-11-01 08:09:16 +00:00
and_(
Shout.id == AuthorBookmark.shout,
AuthorBookmark.author == author_id,
2024-11-01 06:50:19 +00:00
)
2024-11-01 08:09:16 +00:00
)
2024-11-01 06:50:19 +00:00
q, limit, offset = apply_options(q, options, author_id)
return get_shouts_with_links(info, q, limit, offset)
2024-10-21 07:52:23 +00:00
@mutation.field("toggle_bookmark_shout")
def toggle_bookmark_shout(_, info, slug: str) -> CommonResult:
"""
Toggle bookmark status for a specific shout.
Args:
slug (str): Unique identifier of the shout.
Returns:
CommonResult: Result of the operation with bookmark status.
"""
author_dict = info.context.get("author", {})
author_id = author_dict.get("id")
if not author_id:
raise GraphQLError("User not authenticated")
with local_session() as db:
shout = db.query(Shout).filter(Shout.slug == slug).first()
if not shout:
raise GraphQLError("Shout not found")
existing_bookmark = (
db.query(AuthorBookmark)
.filter(AuthorBookmark.author == author_id, AuthorBookmark.shout == shout.id)
.first()
)
if existing_bookmark:
db.execute(
delete(AuthorBookmark).where(AuthorBookmark.author == author_id, AuthorBookmark.shout == shout.id)
)
result = False
else:
db.execute(insert(AuthorBookmark).values(author=author_id, shout=shout.id))
result = True
db.commit()
return result