Untitled
unknown
plain_text
20 days ago
3.2 kB
3
Indexable
Never
public async findFeaturedEvent(teamId: string): Promise<{ data: SportEventDto | null, code: number }> { try { const key = `${RedisKey.CompetitorFeatureMatch}/${teamId}`; const in90Days = 90 * 86400; const in24Hours = 24 * 3600; const timeNow = Math.floor(Date.now() / 1000); const timeOld = timeNow - in90Days; const timeFuture = timeNow + in90Days; const query = ` SELECT s.id, s.season_id, s.stage_id, s.group_num, s.round_num, s.start_timestamp, s.sport_event_status, s.status_id, s.home_team_id, s.away_team_id, s.competition_id, s.lineup, s.venue_id, s.referee_id FROM sport_events s WHERE (s.home_team_id = '${teamId}' OR s.away_team_id = '${teamId}') AND s.start_timestamp BETWEEN ${timeOld} AND ${timeFuture} ORDER BY s.start_timestamp DESC `; // Check cache for the featured event const cachedEvent = await this.redisService.getClient().get(key); if (cachedEvent) { const sportEvent = JSON.parse(cachedEvent); const formattedEvent = this.formatSportEventWithliveMatchAndEndMatch(sportEvent, teamId); return { data: handleEncodeSportEvent(formattedEvent, true), code: CodeRes.FROM_CACHE }; } // Fetch matches from the database const matches = await this.sportEventRepository.query(query) as SportEvent[]; if (matches.length === 0) { return { data: null, code: CodeRes.EMPTY_DATA }; } // Check for the most recent ended match within 24 hours const recentEndedMatch = matches.find((match: SportEvent) => timeNow - in24Hours <= match.start_timestamp && match.start_timestamp <= timeNow ); // Find the most recent upcoming match const upcomingMatch = matches .slice() .reverse() .find((match: SportEvent) => match.status_id === TSMatchState.NotStarted && match.start_timestamp >= timeNow ) || null; if (recentEndedMatch) { const result = await this.convertToSportEventV2([recentEndedMatch]); const timeTTL = in24Hours - (timeNow - recentEndedMatch.start_timestamp); await this.redisService.getClient().set(key, JSON.stringify(result), 'EX', timeTTL); return { data: handleEncodeSportEvent(result, true), code: CodeRes.OK }; } if (upcomingMatch) { const result = await this.convertToSportEventV2([upcomingMatch]); const timeTTL = upcomingMatch.start_timestamp - timeNow + in24Hours; await this.redisService.getClient().set(key, JSON.stringify(result), 'EX', timeTTL); return { data: handleEncodeSportEvent(result, true), code: CodeRes.OK }; } // Special case: if no matches in the future, get the last match const lastMatch = matches[matches.length - 1]; const result = await this.convertToSportEventV2([lastMatch]); await this.redisService.getClient().set(key, JSON.stringify(result), 'EX', in24Hours); return { data: handleEncodeSportEvent(result, true), code: CodeRes.OK }; } catch (err: any) { Logger.error(err.stack, CompetitorService.name); return { data: null, code: CodeRes.ERROR }; } }
Leave a Comment