22import type { DBCommunity } from 'shared/types' ;
33import type { GraphQLContext } from '../../' ;
44import { canViewCommunity } from '../../utils/permissions' ;
5+ import cache from 'shared/cache/redis' ;
56
67export default async ( root : DBCommunity , _ : any , ctx : GraphQLContext ) => {
78 const { user, loaders } = ctx ;
@@ -15,15 +16,49 @@ export default async (root: DBCommunity, _: any, ctx: GraphQLContext) => {
1516 } ;
1617 }
1718
19+ const [
20+ cachedChannelCount ,
21+ cachedMemberCount ,
22+ cachedOnlineMemberCount ,
23+ ] = await Promise . all ( [
24+ cache . get ( `community:${ id } :channelCount` ) ,
25+ cache . get ( `community:${ id } :memberCount` ) ,
26+ cache . get ( `community:${ id } :onlineMemberCount` ) ,
27+ ] ) ;
28+
1829 const [ channelCount , memberCount , onlineMemberCount ] = await Promise . all ( [
19- loaders . communityChannelCount . load ( id ) ,
20- loaders . communityMemberCount . load ( id ) ,
21- loaders . communityOnlineMemberCount . load ( id ) ,
30+ typeof cachedChannelCount === 'number' ||
31+ loaders . communityChannelCount
32+ . load ( id )
33+ . then ( res => ( res && res . reduction ) || 0 ) ,
34+ typeof cachedMemberCount === 'number' ||
35+ loaders . communityMemberCount
36+ . load ( id )
37+ . then ( res => ( res && res . reduction ) || 0 ) ,
38+ typeof cachedOnlineMemberCount === 'number' ||
39+ loaders . communityOnlineMemberCount
40+ . load ( id )
41+ . then ( res => ( res && res . reduction ) || 0 ) ,
42+ ] ) ;
43+
44+ // Cache the fields for an hour
45+ await Promise . all ( [
46+ typeof cachedChannelCount === 'number' ||
47+ cache . set ( `community:${ id } :channelCount` , channelCount , 'ex' , 3600 ) ,
48+ typeof cachedMemberCount === 'number' ||
49+ cache . set ( `community:${ id } :memberCount` , memberCount , 'ex' , 3600 ) ,
50+ typeof cachedOnlineMemberCount === 'number' ||
51+ cache . set (
52+ `community:${ id } :onlineMemberCount` ,
53+ onlineMemberCount ,
54+ 'ex' ,
55+ 3600
56+ ) ,
2257 ] ) ;
2358
2459 return {
25- channels : channelCount ? channelCount . reduction : 0 ,
26- members : memberCount ? memberCount . reduction : 0 ,
27- onlineMembers : onlineMemberCount ? onlineMemberCount . reduction : 0 ,
60+ channels : channelCount ,
61+ members : memberCount ,
62+ onlineMembers : onlineMemberCount ,
2863 } ;
2964} ;
0 commit comments