1
1
"""Various utilities for working with the Discord API."""
2
2
3
- import datetime
4
3
import json
5
4
6
5
import httpx
7
6
import starlette .requests
8
- from pymongo .database import Database
9
7
from starlette import exceptions
10
8
11
9
from backend import constants , models
@@ -66,7 +64,6 @@ async def _get_role_info() -> list[models.DiscordRole]:
66
64
67
65
68
66
async def get_roles (
69
- database : Database ,
70
67
* ,
71
68
force_refresh : bool = False ,
72
69
) -> list [models .DiscordRole ]:
@@ -75,35 +72,17 @@ async def get_roles(
75
72
76
73
If `force_refresh` is True, the cache is skipped and the roles are updated.
77
74
"""
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
107
86
return roles
108
87
109
88
0 commit comments