precached-authors-fix
Some checks are pending
deploy / deploy (push) Waiting to run

This commit is contained in:
2023-12-19 11:25:06 +03:00
parent b2040099a8
commit c3a6ecd3ae
4 changed files with 43 additions and 48 deletions

View File

@@ -1,15 +1,16 @@
from typing import Any, List
import aiohttp
from aiohttp import ClientResponse, ClientSession
from aiohttp import ClientSession
from models.member import ChatMember
from settings import API_BASE
headers = {"Content-Type": "application/json"}
authors_by_user = {}
authors_by_id = {}
async def _request_endpoint(query_name, body) -> Any:
async with aiohttp.ClientSession() as session:
async with ClientSession() as session:
async with session.post(API_BASE, headers=headers, json=body) as response:
print(f"[services.core] {query_name} response: <{response.status}> {await response.text()}")
if response.status == 200:
@@ -19,21 +20,27 @@ async def _request_endpoint(query_name, body) -> Any:
return []
async def get_all_authors(limit: int = 50, offset: int = 0) -> List[ChatMember]:
query_name = "load_authors_all"
async def get_all_authors() -> List[ChatMember]:
if len(authors_by_user.keys()) == 0:
query_name = "get_authors_all"
gql = {
"query": "query { "
+ query_name
+ "(limit: "
+ str(limit)
+ ", offset: "
+ str(offset)
+ ") { id slug pic name } }",
"variables": None,
}
# Check if authors are already cached
if "authors" in authors_by_user:
return authors_by_user["authors"]
return await _request_endpoint(query_name, gql)
gql = {
"query": "query { " + query_name + "{ id slug pic name } }",
"variables": None,
}
# Make a request to load authors
authors = await _request_endpoint(query_name, gql)
for a in authors:
authors_by_user[a.user] = a
authors_by_id[a.id] = a
return authors_by_id.values()
async def get_my_followed() -> List[ChatMember]:
@@ -48,16 +55,4 @@ async def get_my_followed() -> List[ChatMember]:
async def get_author(user: str = ""):
query_name = "get_author_id"
operation = "GetAuthorId"
gql = {
"query": f"query {operation}($user: String!) {{ {query_name}(user: $user) {{ id slug pic name }} }}",
"operationName": operation,
"variables": {"user": user},
}
r = await _request_endpoint(query_name, gql)
if r and isinstance(r, list):
r = r.pop()
return r or None
return authors_by_user.get(user)