resolvers-updates
Some checks failed
deploy / deploy (push) Failing after 1m30s

This commit is contained in:
Untone 2023-12-16 18:24:30 +03:00
parent bf7bc03e50
commit 692dd9cfe0
7 changed files with 171 additions and 34 deletions

View File

@ -35,7 +35,7 @@ poetry run python server.py
### Auth
Put the header 'Authorization' with token from signIn query or registerUser mutation. Setup `WEBHOOK_SECRET` env var
Setup `WEBHOOK_SECRET` env var, webhook payload on `/new-author` is expected when User is created. In front-end put the header 'Authorization' with token from signIn query or registerUser mutation.
### Viewed

21
main.py
View File

@ -4,6 +4,7 @@ from importlib import import_module
from os.path import exists
from ariadne import load_schema_from_path, make_executable_schema
from ariadne.asgi import GraphQL
from sqlalchemy.exc import IntegrityError
from sentry_sdk.integrations.ariadne import AriadneIntegration
from sentry_sdk.integrations.redis import RedisIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
@ -58,25 +59,5 @@ async def shutdown():
await redis.disconnect()
class WebhookEndpoint(HTTPEndpoint):
async def post(self, request: Request) -> JSONResponse:
try:
data = await request.json()
if data:
auth = request.headers.get("Authorization")
if auth:
if auth == os.environ.get("WEBHOOK_SECRET"):
user_id: str = data["user"]["id"]
slug: str = data["user"]["email"].split("@")[0]
slug: str = re.sub("[^0-9a-z]+", "-", slug.lower())
await create_author(user_id, slug)
return JSONResponse({"status": "success"})
except Exception as e:
import traceback
traceback.print_exc()
return JSONResponse({"status": "error", "message": str(e)}, status_code=500)
routes = [Route("/", GraphQL(schema, debug=True)), Route("/new-author", WebhookEndpoint)]
app = Starlette(routes=routes, debug=True, on_startup=[start_up], on_shutdown=[shutdown])

View File

@ -26,7 +26,14 @@ from resolvers.topic import (
)
from resolvers.follower import follow, unfollow, get_my_followed
from resolvers.reader import get_shout, load_shouts_by, load_shouts_feed, load_shouts_search
from resolvers.reader import (
get_shout,
load_shouts_by,
load_shouts_feed,
load_shouts_search,
load_shouts_unrated,
load_shouts_random_top,
)
from resolvers.community import get_community, get_communities_all
__all__ = [
@ -53,6 +60,8 @@ __all__ = [
"load_shouts_feed",
"load_shouts_search",
"load_shouts_followed",
"load_shouts_unrated",
"load_shouts_random_top",
# follower
"follow",
"unfollow",

View File

@ -96,7 +96,7 @@ def get_authors_from_query(q):
for [author, *stat_columns] in session.execute(q):
author = add_stat(author, stat_columns)
authors.append(author)
print(f"[resolvers.author] get_authors_from_query {authors}")
# print(f"[resolvers.author] get_authors_from_query {authors}")
return authors

View File

@ -102,7 +102,10 @@ async def get_shout(_, _info, slug=None, shout_id=None):
author.caption = author_caption.caption
main_topic = (
session.query(Topic.slug)
.join(ShoutTopic, and_(ShoutTopic.topic == Topic.id, ShoutTopic.shout == shout.id, ShoutTopic.main == True))
.join(
ShoutTopic,
and_(ShoutTopic.topic == Topic.id, ShoutTopic.shout == shout.id, ShoutTopic.main == True),
)
.first()
)
@ -168,7 +171,10 @@ async def load_shouts_by(_, _info, options):
for [shout, reacted_stat, commented_stat, rating_stat, _last_comment] in session.execute(q).unique():
main_topic = (
session.query(Topic.slug)
.join(ShoutTopic, and_(ShoutTopic.topic == Topic.id, ShoutTopic.shout == shout.id, ShoutTopic.main == True))
.join(
ShoutTopic,
and_(ShoutTopic.topic == Topic.id, ShoutTopic.shout == shout.id, ShoutTopic.main == True),
)
.first()
)
@ -209,7 +215,10 @@ async def load_shouts_drafts(_, info):
for [shout] in session.execute(q).unique():
main_topic = (
session.query(Topic.slug)
.join(ShoutTopic, and_(ShoutTopic.topic == Topic.id, ShoutTopic.shout == shout.id, ShoutTopic.main == True))
.join(
ShoutTopic,
and_(ShoutTopic.topic == Topic.id, ShoutTopic.shout == shout.id, ShoutTopic.main == True),
)
.first()
)
@ -235,10 +244,7 @@ async def load_shouts_feed(_, info, options):
select(Shout.id)
.where(Shout.id == ShoutAuthor.shout)
.where(Shout.id == ShoutTopic.shout)
.where(
(ShoutAuthor.user.in_(reader_followed_authors))
| (ShoutTopic.topic.in_(reader_followed_topics))
)
.where((ShoutAuthor.user.in_(reader_followed_authors)) | (ShoutTopic.topic.in_(reader_followed_topics)))
)
q = (
@ -247,9 +253,7 @@ async def load_shouts_feed(_, info, options):
joinedload(Shout.authors),
joinedload(Shout.topics),
)
.where(
and_(Shout.published_at.is_not(None), Shout.deleted_at.is_(None), Shout.id.in_(subquery))
)
.where(and_(Shout.published_at.is_not(None), Shout.deleted_at.is_(None), Shout.id.in_(subquery)))
)
q = add_stat_columns(q)
@ -269,7 +273,10 @@ async def load_shouts_feed(_, info, options):
for [shout, reacted_stat, commented_stat, rating_stat, _last_comment] in session.execute(q).unique():
main_topic = (
session.query(Topic.slug)
.join(ShoutTopic, and_(ShoutTopic.topic == Topic.id, ShoutTopic.shout == shout.id, ShoutTopic.main == True))
.join(
ShoutTopic,
and_(ShoutTopic.topic == Topic.id, ShoutTopic.shout == shout.id, ShoutTopic.main == True),
)
.first()
)
@ -293,3 +300,106 @@ async def load_shouts_search(_, _info, text, limit=50, offset=0):
else:
return []
@query.field("load_shouts_unrated")
async def load_shouts_unrated(_, info, limit, offset=0):
q = (
select(Shout)
.options(
joinedload(Shout.authors),
joinedload(Shout.topics),
)
.outerjoin(
Reaction,
and_(
Reaction.shout == Shout.id,
Reaction.replyTo.is_(None),
Reaction.kind.in_([ReactionKind.LIKE, ReactionKind.DISLIKE]),
),
)
.where(and_(Shout.deletedAt.is_(None), Shout.layout.is_not(None), Reaction.id.is_(None)))
)
q = add_stat_columns(q)
q = q.group_by(Shout.id).order_by(desc(Shout.createdAt)).limit(limit).offset(offset)
# print(q.compile(compile_kwargs={"literal_binds": True}))
return get_shouts_from_query(q)
def get_shouts_from_query(q):
shouts = []
with local_session() as session:
for [shout, reacted_stat, commented_stat, rating_stat, last_comment] in session.execute(q).unique():
shouts.append(shout)
shout.stat = {
"viewed": shout.views,
"reacted": reacted_stat,
"commented": commented_stat,
"rating": rating_stat,
}
return shouts
def get_rating_func(aliased_reaction):
return func.sum(
case(
(aliased_reaction.kind == ReactionKind.AGREE.value, 1),
(aliased_reaction.kind == ReactionKind.DISAGREE.value, -1),
(aliased_reaction.kind == ReactionKind.PROOF.value, 1),
(aliased_reaction.kind == ReactionKind.DISPROOF.value, -1),
(aliased_reaction.kind == ReactionKind.ACCEPT.value, 1),
(aliased_reaction.kind == ReactionKind.REJECT.value, -1),
(aliased_reaction.kind == ReactionKind.LIKE.value, 1),
(aliased_reaction.kind == ReactionKind.DISLIKE.value, -1),
(aliased_reaction.reply_to.is_not(None), 0),
else_=0,
)
)
@query.field("load_shouts_random_top")
async def load_shouts_random_top(_, _info, params):
"""
:param params: {
filters: {
layouts: ['music']
after: 13245678
fromRandomCount: 100,
limit: 50
offset: 0
}
:return: Shout[]
"""
aliased_reaction = aliased(Reaction)
subquery = select(Shout.id).outerjoin(aliased_reaction).where(Shout.deleted_at.is_(None))
subquery = apply_filters(subquery, params.get("filters", {}))
subquery = subquery.group_by(Shout.id).order_by(desc(get_rating_func(aliased_reaction)))
from_random_count = params.get("fromRandomCount")
if from_random_count:
subquery = subquery.limit(from_random_count)
q = (
select(Shout)
.options(
joinedload(Shout.authors),
joinedload(Shout.topics),
)
.where(Shout.id.in_(subquery))
)
q = add_stat_columns(q)
limit = params.get("limit", 10)
q = q.group_by(Shout.id).order_by(func.random()).limit(limit)
# print(q.compile(compile_kwargs={"literal_binds": True}))
return get_shouts_from_query(q)

35
resolvers/webhook.py Normal file
View File

@ -0,0 +1,35 @@
import os
import re
from starlette.endpoints import HTTPEndpoint
from starlette.requests import Request
from starlette.responses import JSONResponse
from orm.author import Author
from resolvers.author import create_author
from services.db import local_session
class WebhookEndpoint(HTTPEndpoint):
async def post(self, request: Request) -> JSONResponse:
try:
data = await request.json()
if data:
auth = request.headers.get("Authorization")
if auth:
if auth == os.environ.get("WEBHOOK_SECRET"):
user_id: str = data["user"]["id"]
slug: str = data["user"]["email"].split("@")[0]
slug: str = re.sub("[^0-9a-z]+", "-", slug.lower())
with local_session() as session:
author = session.query(Author).filter(Author.slug == slug).first()
if author:
slug = slug + "-" + user_id.split("-").pop()
await create_author(user_id, slug)
return JSONResponse({"status": "success"})
except Exception as e:
import traceback
traceback.print_exc()
return JSONResponse({"status": "error", "message": str(e)}, status_code=500)

View File

@ -358,6 +358,8 @@ type Query {
load_shouts_by(options: LoadShoutsOptions): [Shout]
load_shouts_search(text: String!, limit: Int, offset: Int): [Shout]
load_shouts_feed(options: LoadShoutsOptions): [Shout]
load_shouts_unrated(limit: Int, offset: Int): [Shout]
load_shouts_random_top(options: LoadShoutsOptions): [Shout]
load_shouts_drafts: [Shout]
# topic