11"""Various utilities for working with the Discord API."""
22
3- import datetime
43import json
54
65import httpx
76import starlette .requests
8- from pymongo .database import Database
97from starlette import exceptions
108
119from backend import constants , models
@@ -66,7 +64,6 @@ async def _get_role_info() -> list[models.DiscordRole]:
6664
6765
6866async def get_roles (
69- database : Database ,
7067 * ,
7168 force_refresh : bool = False ,
7269) -> list [models .DiscordRole ]:
@@ -75,35 +72,17 @@ async def get_roles(
7572
7673 If `force_refresh` is True, the cache is skipped and the roles are updated.
7774 """
78- collection = database .get_collection ("roles" )
79-
80- if force_refresh :
81- # Drop all values in the collection
82- await collection .delete_many ({})
83-
84- # `create_index` creates the index if it does not exist, or passes
85- # This handles TTL on role objects
86- await collection .create_index (
87- "inserted_at" ,
88- expireAfterSeconds = 60 * 60 * 24 , # 1 day
89- name = "inserted_at" ,
90- )
91-
92- roles = [models .DiscordRole (** json .loads (role ["data" ])) async for role in collection .find ()]
93-
94- if len (roles ) == 0 :
95- # Fetch roles from the API and insert into the database
96- roles = await _get_role_info ()
97- await collection .insert_many (
98- {
99- "name" : role .name ,
100- "id" : role .id ,
101- "data" : role .json (),
102- "inserted_at" : datetime .datetime .now (tz = datetime .UTC ),
103- }
104- for role in roles
105- )
106-
75+ role_cache_key = "forms-backend:role_cache"
76+ if not force_refresh :
77+ roles = await constants .REDIS_CLIENT .hgetall (role_cache_key )
78+ if roles :
79+ return [
80+ models .DiscordRole (** json .loads (role_data )) for role_id , role_data in roles .items ()
81+ ]
82+
83+ roles = await _get_role_info ()
84+ await constants .REDIS_CLIENT .hmset (role_cache_key , {role .id : role .json () for role in roles })
85+ await constants .REDIS_CLIENT .expire (role_cache_key , 60 * 60 * 24 ) # 1 day
10786 return roles
10887
10988
0 commit comments