import { Injectable, Logger } from '@nestjs/common'; import { RedisService } from '../global/redis/redis.service'; const COMMUNITY_STATS_TTL_SECONDS = 5 * 60; const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60; @Injectable() export class CommunityStatsCacheService { private readonly logger = new Logger(CommunityStatsCacheService.name); constructor(private readonly redisService: RedisService) {} public get(key: string): Promise { return this.redisService.getJson(key); } public set( key: string, value: unknown, ttlSeconds = COMMUNITY_STATS_TTL_SECONDS, ): Promise { return this.redisService.setJson(key, value, ttlSeconds); } public setDetail(key: string, value: unknown): Promise { return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS); } public async invalidateCommunity(communityId: string): Promise { const prefix = `riot:communitystats:`; const match = `${prefix}*${communityId}*`; const client = this.redisService.raw(); let cursor = '0'; let deleted = 0; do { const reply = await client.sendCommand([ 'SCAN', cursor, 'MATCH', match, 'COUNT', '100', ]); if (!Array.isArray(reply)) { throw new Error('Redis SCAN returned an invalid response.'); } const values = reply as unknown[]; const nextCursor = values[0]; const rawKeys = values[1]; if (typeof nextCursor !== 'string') { throw new Error('Redis SCAN returned an invalid cursor.'); } cursor = nextCursor; const keys = Array.isArray(rawKeys) ? (rawKeys as unknown[]).filter( (key): key is string => typeof key === 'string', ) : []; if (keys.length > 0) { deleted += await client.del(keys); } } while (cursor !== '0'); if (deleted > 0) { this.logger.debug( `Invalidated ${deleted} community stats cache keys for ${communityId}.`, ); } return deleted; } }