Skip to content

Commit 5c20e6e

Browse files
committed
add caching to stats query
1 parent 6cfbe79 commit 5c20e6e

1 file changed

Lines changed: 23 additions & 18 deletions

File tree

api/schema/stats_schema.py

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import strawberry
44
import strawberry_django
5+
from django.core.cache import cache
56
from django.db.models import Count, Q
67
from strawberry.types import Info
78

@@ -12,6 +13,9 @@
1213
from api.utils.graphql_telemetry import trace_resolver
1314
from authorization.models import User
1415

16+
STATS_CACHE_KEY = "platform_stats"
17+
STATS_CACHE_TTL = 60 * 10 # 10 minutes
18+
1519

1620
@strawberry.type
1721
class StatsType:
@@ -31,20 +35,20 @@ class Query:
3135
@trace_resolver(name="stats", attributes={"component": "stats"})
3236
def stats(self, info: Info) -> StatsType:
3337
"""Get platform statistics"""
38+
cached = cache.get(STATS_CACHE_KEY)
39+
if cached:
40+
return StatsType(**cached)
41+
3442
# Count total users
3543
total_users = User.objects.count()
3644

3745
# Count published datasets
38-
total_published_datasets = Dataset.objects.filter(
39-
status=DatasetStatus.PUBLISHED
40-
).count()
46+
total_published_datasets = Dataset.objects.filter(status=DatasetStatus.PUBLISHED).count()
4147

4248
# Count publishers (organizations and individuals who have published datasets)
4349
# First, get organizations that have published datasets
4450
org_publishers = (
45-
Organization.objects.filter(datasets__status=DatasetStatus.PUBLISHED)
46-
.distinct()
47-
.count()
51+
Organization.objects.filter(datasets__status=DatasetStatus.PUBLISHED).distinct().count()
4852
)
4953

5054
# Then, get individual users who have published datasets
@@ -61,15 +65,16 @@ def stats(self, info: Info) -> StatsType:
6165
total_publishers = org_publishers + individual_publishers
6266

6367
# Count published usecases
64-
total_published_usecases = UseCase.objects.filter(
65-
status=UseCaseStatus.PUBLISHED
66-
).count()
67-
68-
return StatsType(
69-
total_users=total_users,
70-
total_published_datasets=total_published_datasets,
71-
total_publishers=total_publishers,
72-
total_organizations=org_publishers,
73-
total_individuals=individual_publishers,
74-
total_published_usecases=total_published_usecases,
75-
)
68+
total_published_usecases = UseCase.objects.filter(status=UseCaseStatus.PUBLISHED).count()
69+
70+
stats_data = {
71+
"total_users": total_users,
72+
"total_published_datasets": total_published_datasets,
73+
"total_publishers": total_publishers,
74+
"total_organizations": org_publishers,
75+
"total_individuals": individual_publishers,
76+
"total_published_usecases": total_published_usecases,
77+
}
78+
cache.set(STATS_CACHE_KEY, stats_data, timeout=STATS_CACHE_TTL)
79+
80+
return StatsType(**stats_data)

0 commit comments

Comments
 (0)