inbox/services/core.py
Untone fa79164ca8
All checks were successful
deploy / deploy (push) Successful in 1m5s
cached-request-4
2023-12-19 19:17:01 +03:00

73 lines
2.2 KiB
Python

from typing import List
import requests
from models.member import ChatMember
from settings import API_BASE
from datetime import datetime, timedelta
# Global variables to store cached authors data and last update time
cached_authors = None
last_update_time = None
update_interval = timedelta(minutes=2)
def _request_endpoint(query_name, body) -> dict:
print(f"[services.core] requesting {query_name}...")
response = requests.post(API_BASE, headers={"Content-Type": "application/json"}, json=body)
print(f"[services.core] {query_name} response: <{response.status_code}> {response.text[:65]}..")
if response.status_code == 200:
try:
r = response.json()
result = r.get("data", {}).get(query_name, {})
print(f"[services.core] entries amount in result: {len(result)} ")
return result
except ValueError as e:
print(f"[services.core] Error decoding JSON response: {e}")
return {}
def get_all_authors():
global cached_authors, last_update_time
# Check if cached data is available and not expired
if cached_authors is not None and (datetime.now() - last_update_time) < update_interval:
print("[services.core] Returning cached authors data")
return cached_authors
authors_by_user = {}
authors_by_id = {}
query_name = "get_authors_all"
gql = {
"query": "query { " + query_name + "{ id slug pic name user } }",
"variables": None,
}
# Make a request to load authors
authors = _request_endpoint(query_name, gql)
for a in list(authors):
authors_by_user[a["user"]] = a
authors_by_id[a["id"]] = a
# Cache the authors data and update the last update time
cached_authors = authors_by_user, authors_by_id
last_update_time = datetime.now()
return authors_by_user, authors_by_id
def get_my_followed() -> List[ChatMember]:
query_name = "get_my_followed"
gql = {
"query": "query { " + query_name + " { authors { id slug pic name } } }",
"variables": None,
}
return _request_endpoint(query_name, gql).get(
"authors", []
) # Ensure you're returning the correct part of the response