diff --git a/services/core.py b/services/core.py index 4def285..b75dbca 100644 --- a/services/core.py +++ b/services/core.py @@ -1,21 +1,18 @@ -from functools import lru_cache -from typing import Any, 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) -@lru_cache(maxsize=128, typed=True) -def __request_endpoint(query_name, body) -> requests.Response: +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]}..") - return response - - -def _request_endpoint(query_name, body) -> Any: - response = __request_endpoint(query_name, body) if response.status_code == 200: try: @@ -26,18 +23,21 @@ def _request_endpoint(query_name, body) -> Any: except ValueError as e: print(f"[services.core] Error decoding JSON response: {e}") - return [] + 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" - # Check if authors are already cached - if "authors" in authors_by_user: - return authors_by_user["authors"] - gql = { "query": "query { " + query_name + "{ id slug pic name user } }", "variables": None, @@ -50,6 +50,10 @@ def get_all_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 @@ -61,4 +65,6 @@ def get_my_followed() -> List[ChatMember]: "variables": None, } - return _request_endpoint(query_name, gql) or [] + return _request_endpoint(query_name, gql).get( + "authors", [] + ) # Ensure you're returning the correct part of the response