@@ -488,7 +488,19 @@ export interface CoalitionScore {
488488 totalContributors : number ;
489489} ;
490490
491+ const scoreCache = new NodeCache ( {
492+ stdTTL : 60 * 10 , // 10 minutes
493+ checkperiod : 60 * 2 , // 2 minutes
494+ useClones : false ,
495+ } ) ;
496+
491497export const getCoalitionScore = async function ( prisma : PrismaClient , coalitionId : number , atDateTime : Date = new Date ( ) ) : Promise < CoalitionScore > {
498+ // Check cache first
499+ const cachedScore = scoreCache . get < CoalitionScore > ( `coalitionScore_${ coalitionId } _${ atDateTime . getTime ( ) } ` ) ;
500+ if ( cachedScore ) {
501+ return cachedScore ;
502+ }
503+
492504 const scoreStatistics = await getScoreStatistics ( prisma , coalitionId , atDateTime ) ;
493505
494506 const totalMembers = await prisma . intraCoalitionUser . count ( {
@@ -508,7 +520,7 @@ export const getCoalitionScore = async function(prisma: PrismaClient, coalitionI
508520
509521 const totalContributors = Math . min ( scoreStatistics . dataPoints . length , totalMembers ) ;
510522
511- return {
523+ const score : CoalitionScore = {
512524 coalition_id : coalitionId ,
513525 totalPoints : scoreStatistics . sum ,
514526 avgPoints : scoreStatistics . mean ,
@@ -517,6 +529,30 @@ export const getCoalitionScore = async function(prisma: PrismaClient, coalitionI
517529 totalMembers : totalMembers ,
518530 totalContributors : totalContributors ,
519531 } ;
532+
533+ // Cache the result, depending on how long ago it was, cache it for longer and longer periods of time.
534+ // Past week: do not cache (scores could still change due to late submissions)
535+ // 1 week ago: cache for 1 hour
536+ // 2 weeks ago: cache for 6 hours
537+ // 3 weeks ago: cache for 1 day
538+ const now = new Date ( ) ;
539+ const diffMs = now . getTime ( ) - atDateTime . getTime ( ) ;
540+ const diffDays = diffMs / ( 1000 * 60 * 60 * 24 ) ;
541+ let cacheTime = 0 ;
542+ if ( diffDays >= 21 ) {
543+ cacheTime = 60 * 60 * 24 ; // 1 day
544+ }
545+ else if ( diffDays >= 14 ) {
546+ cacheTime = 60 * 60 * 6 ; // 6 hours
547+ }
548+ else if ( diffDays >= 7 ) {
549+ cacheTime = 60 * 60 ; // 1 hour
550+ }
551+ if ( cacheTime > 0 ) {
552+ scoreCache . set ( `coalitionScore_${ coalitionId } _${ atDateTime . getTime ( ) } ` , score , cacheTime ) ;
553+ }
554+
555+ return score ;
520556} ;
521557
522558export interface SingleRanking {
0 commit comments