feat(api): add community stats API
This commit is contained in:
1 parent
fc81beec45
commit
b3b59d37fc
5 files changed
+1392
No files matched your search
@@ -0,0 +1,992 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type { CommunityDocument, RiotLane } from '../global/database/schema';
|
||||
import type {
|
||||
HistorySeasonDto,
|
||||
RecentMatchView,
|
||||
} from '../match-history/match-history.types';
|
||||
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
||||
import type {
|
||||
CommunityStatsFilters,
|
||||
InternalMatchCardView,
|
||||
InternalMatchDetailResponse,
|
||||
InternalMatchListResponse,
|
||||
LeaderboardChampionStats,
|
||||
LeaderboardResponse,
|
||||
LeaderboardRow,
|
||||
LeaderHighlight,
|
||||
TeamInsightsResponse,
|
||||
UserInternalHistoryResponse,
|
||||
} from './community-stats.types';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
import { MatchStatsService } from './match-stats.service';
|
||||
import {
|
||||
InternalGameDetail,
|
||||
InternalRecord,
|
||||
MATCH_STATS_BUILDER_VERSION,
|
||||
} from './match-stats.types';
|
||||
|
||||
const DEFAULT_LIST_LIMIT = 20;
|
||||
const MAX_LIST_LIMIT = 50;
|
||||
const MAX_MATCH_SCAN = 300;
|
||||
const MIN_HIGHLIGHT_GAMES = 5;
|
||||
|
||||
interface CommunityStatsContext {
|
||||
community: CommunityDocument;
|
||||
season: HistorySeasonDto;
|
||||
from: Date | null;
|
||||
to: Date | null;
|
||||
}
|
||||
|
||||
interface BaseDataset {
|
||||
season: HistorySeasonDto;
|
||||
matches: InternalMatchCardView[];
|
||||
records: InternalRecord[];
|
||||
detailsByMatchId: Map<string, InternalGameDetail[]>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class CommunityStatsService {
|
||||
private readonly logger = new Logger(CommunityStatsService.name);
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly cacheService: CommunityStatsCacheService,
|
||||
private readonly matchStatsRepository: MatchStatsRepository,
|
||||
private readonly matchStatsService: MatchStatsService,
|
||||
) {}
|
||||
|
||||
public async getMatches(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
filters: CommunityStatsFilters;
|
||||
}): Promise<InternalMatchListResponse> {
|
||||
const key = this.cacheKey('matches', params.communityId, params.filters);
|
||||
const cached = await this.cacheService.get<InternalMatchListResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const limit = this.clampLimit(
|
||||
params.filters.limit,
|
||||
DEFAULT_LIST_LIMIT,
|
||||
MAX_LIST_LIMIT,
|
||||
);
|
||||
const dataset = await this.buildBaseDataset(
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const filtered = params.filters.championId
|
||||
? dataset.matches.filter((match) =>
|
||||
dataset.records.some(
|
||||
(record) =>
|
||||
record.matchId === match.matchId &&
|
||||
record.championId === params.filters.championId,
|
||||
),
|
||||
)
|
||||
: dataset.matches;
|
||||
const cursor = params.filters.cursor;
|
||||
const page = filtered
|
||||
.filter(
|
||||
(match) => !cursor || new Date(match.scheduledAt).getTime() < cursor,
|
||||
)
|
||||
.slice(0, limit + 1);
|
||||
const visible = page.slice(0, limit);
|
||||
const response: InternalMatchListResponse = {
|
||||
matches: visible,
|
||||
nextCursor:
|
||||
page.length > limit
|
||||
? new Date(visible[visible.length - 1]?.scheduledAt ?? 0).getTime()
|
||||
: null,
|
||||
season: dataset.season,
|
||||
};
|
||||
await this.cacheService.set(key, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
public async getLeaderboard(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
filters: CommunityStatsFilters;
|
||||
}): Promise<LeaderboardResponse> {
|
||||
const key = this.cacheKey(
|
||||
'leaderboard',
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const cached = await this.cacheService.get<LeaderboardResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const dataset = await this.buildBaseDataset(
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const records = this.applyChampionFilter(dataset.records, params.filters);
|
||||
const rows = this.buildLeaderboardRows(records);
|
||||
const response = { rows, season: dataset.season };
|
||||
await this.cacheService.set(key, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
public async getTeamInsights(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
filters: CommunityStatsFilters;
|
||||
}): Promise<TeamInsightsResponse> {
|
||||
const key = this.cacheKey(
|
||||
'teamInsights',
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const cached = await this.cacheService.get<TeamInsightsResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const dataset = await this.buildBaseDataset(
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const records = this.applyChampionFilter(dataset.records, params.filters);
|
||||
const rows = this.buildLeaderboardRows(records);
|
||||
const gameDetails = [...dataset.detailsByMatchId.values()].flat();
|
||||
const blueGames = gameDetails.length;
|
||||
const redGames = gameDetails.length;
|
||||
const blueWins = gameDetails.filter(
|
||||
(game) => game.winnerSide === 'blue',
|
||||
).length;
|
||||
const redWins = gameDetails.filter(
|
||||
(game) => game.winnerSide === 'red',
|
||||
).length;
|
||||
|
||||
const response: TeamInsightsResponse = {
|
||||
season: dataset.season,
|
||||
sideWinRate: {
|
||||
blue: this.percent(blueWins, blueGames),
|
||||
red: this.percent(redWins, redGames),
|
||||
bluePicks: blueGames,
|
||||
redPicks: redGames,
|
||||
},
|
||||
topKda: this.toHighlight(
|
||||
rows
|
||||
.filter((row) => row.games >= MIN_HIGHLIGHT_GAMES)
|
||||
.sort((left, right) => right.kda - left.kda)[0],
|
||||
'kda',
|
||||
),
|
||||
mostKills: this.toHighlight(
|
||||
rows.sort((left, right) => right.totalKills - left.totalKills)[0],
|
||||
'totalKills',
|
||||
),
|
||||
topTeamGpm: this.toSingleGameHighlight(
|
||||
records.sort((left, right) => right.gpm - left.gpm)[0],
|
||||
'gpm',
|
||||
),
|
||||
topKillParticipation: this.toHighlight(
|
||||
rows
|
||||
.filter((row) => row.games >= MIN_HIGHLIGHT_GAMES)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.avgKillParticipation - left.avgKillParticipation,
|
||||
)[0],
|
||||
'avgKillParticipation',
|
||||
),
|
||||
bestFarm: this.toHighlight(
|
||||
rows
|
||||
.filter((row) => row.games >= MIN_HIGHLIGHT_GAMES)
|
||||
.sort((left, right) => right.avgCsPerMin - left.avgCsPerMin)[0],
|
||||
'avgCsPerMin',
|
||||
),
|
||||
minGamesThreshold: MIN_HIGHLIGHT_GAMES,
|
||||
};
|
||||
await this.cacheService.set(key, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
public async getMatchDetail(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
}): Promise<InternalMatchDetailResponse> {
|
||||
const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`;
|
||||
const cached =
|
||||
await this.cacheService.get<InternalMatchDetailResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const dataset = await this.buildBaseDataset(params.communityId, {
|
||||
seasonId: 'all',
|
||||
});
|
||||
const match = dataset.matches.find(
|
||||
(item) => item.matchId === params.matchId.toString(),
|
||||
);
|
||||
if (!match) throw new NotFoundException('Internal match not found.');
|
||||
const response: InternalMatchDetailResponse = {
|
||||
match,
|
||||
games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map(
|
||||
(game) => ({
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
teams: game.teams.map((team) => ({
|
||||
teamIndex: team.teamIndex,
|
||||
side: team.side,
|
||||
win: team.win,
|
||||
objectives: team.objectives,
|
||||
participants: team.participants.map((record) => ({
|
||||
userId: record.userId,
|
||||
summonerName: record.summonerName,
|
||||
teamIndex: record.teamIndex,
|
||||
side: record.side,
|
||||
teamPosition: record.teamPosition,
|
||||
championId: record.championId,
|
||||
kills: record.kills,
|
||||
deaths: record.deaths,
|
||||
assists: record.assists,
|
||||
cs: record.cs,
|
||||
csPerMin: record.csPerMin,
|
||||
gold: record.gold,
|
||||
gpm: record.gpm,
|
||||
damageDealtToChampions: record.damageDealtToChampions,
|
||||
damageShare: record.damageShare,
|
||||
killParticipation: record.killParticipation,
|
||||
visionScore: record.visionScore,
|
||||
items: record.items,
|
||||
trinket: record.trinket,
|
||||
summonerSpells: record.summonerSpells,
|
||||
perks: record.perks,
|
||||
win: record.win,
|
||||
})),
|
||||
})),
|
||||
}),
|
||||
),
|
||||
};
|
||||
await this.cacheService.setDetail(key, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
public async getUserInternalHistory(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
filters: CommunityStatsFilters;
|
||||
}): Promise<UserInternalHistoryResponse> {
|
||||
const key = this.cacheKey(
|
||||
`userInternal:${params.userId.toString()}`,
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const cached =
|
||||
await this.cacheService.get<UserInternalHistoryResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const dataset = await this.buildBaseDataset(
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const allUserRecords = dataset.records
|
||||
.filter((record) => record.userId === params.userId.toString())
|
||||
.sort((left, right) => right.gameCreation - left.gameCreation);
|
||||
const records = this.applyChampionFilter(allUserRecords, params.filters);
|
||||
const limit = this.clampLimit(params.filters.limit, 30, 50);
|
||||
const cursor = params.filters.cursor;
|
||||
const page = records
|
||||
.filter((record) => !cursor || record.gameCreation < cursor)
|
||||
.slice(0, limit + 1);
|
||||
const visible = page.slice(0, limit);
|
||||
const response: UserInternalHistoryResponse = {
|
||||
season: dataset.season,
|
||||
championStats: this.buildUserChampionStats(
|
||||
allUserRecords,
|
||||
dataset.season,
|
||||
),
|
||||
summary: this.buildUserSummary(records, visible.length || limit),
|
||||
matches: visible.map((record) => this.toRecentMatchView(record, dataset)),
|
||||
nextCursor:
|
||||
page.length > limit
|
||||
? (visible[visible.length - 1]?.gameCreation ?? null)
|
||||
: null,
|
||||
lastFetchedAt: records[0]
|
||||
? new Date(records[0].gameCreation).toISOString()
|
||||
: null,
|
||||
};
|
||||
await this.cacheService.set(key, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
public invalidateCommunity(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<number> {
|
||||
return this.cacheService.invalidateCommunity(communityId.toString());
|
||||
}
|
||||
|
||||
private async buildBaseDataset(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
filters: CommunityStatsFilters,
|
||||
): Promise<BaseDataset> {
|
||||
const context = await this.resolveContext(communityId, filters);
|
||||
let fragments = await this.matchStatsRepository.findByCommunity({
|
||||
communityId,
|
||||
fromGameCreation: context.from?.getTime(),
|
||||
toGameCreation: context.to?.getTime(),
|
||||
limit: MAX_MATCH_SCAN,
|
||||
});
|
||||
const rebuilt = await this.rebuildMissingOrStaleFragments(communityId);
|
||||
if (rebuilt > 0) {
|
||||
fragments = await this.matchStatsRepository.findByCommunity({
|
||||
communityId,
|
||||
fromGameCreation: context.from?.getTime(),
|
||||
toGameCreation: context.to?.getTime(),
|
||||
limit: MAX_MATCH_SCAN,
|
||||
});
|
||||
}
|
||||
|
||||
const cards: InternalMatchCardView[] = [];
|
||||
const records: InternalRecord[] = [];
|
||||
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
|
||||
|
||||
for (const fragment of fragments) {
|
||||
const filteredGames = (fragment.gameDetails as InternalGameDetail[])
|
||||
.filter((game) => this.isGameInRange(game.gameCreation, context))
|
||||
.sort((left, right) => left.gameNumber - right.gameNumber);
|
||||
if (filteredGames.length === 0) continue;
|
||||
|
||||
const card = this.adjustCardForRange(
|
||||
fragment.matchCard as unknown as InternalMatchCardView,
|
||||
filteredGames,
|
||||
);
|
||||
cards.push(card);
|
||||
detailsByMatchId.set(fragment.matchId.toString(), filteredGames);
|
||||
|
||||
const allowedGameNumbers = new Set(
|
||||
filteredGames.map((game) => game.gameNumber),
|
||||
);
|
||||
records.push(
|
||||
...(fragment.records as InternalRecord[]).filter((record) =>
|
||||
allowedGameNumbers.has(record.gameNumber),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
season: context.season,
|
||||
matches: cards,
|
||||
records,
|
||||
detailsByMatchId,
|
||||
};
|
||||
}
|
||||
|
||||
private async rebuildMissingOrStaleFragments(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<number> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const [matches, fragments] = await Promise.all([
|
||||
MatchModel.find({
|
||||
communityId,
|
||||
status: { $in: ['finished', 'in-progress'] },
|
||||
'result.games.0': { $exists: true },
|
||||
})
|
||||
.sort({ scheduledAt: -1 })
|
||||
.limit(MAX_MATCH_SCAN)
|
||||
.select({ _id: 1 })
|
||||
.exec(),
|
||||
this.matchStatsRepository.findByCommunity({
|
||||
communityId,
|
||||
limit: MAX_MATCH_SCAN,
|
||||
}),
|
||||
]);
|
||||
const fragmentByMatchId = new Map(
|
||||
fragments.map((fragment) => [fragment.matchId.toString(), fragment]),
|
||||
);
|
||||
let rebuilt = 0;
|
||||
|
||||
for (const match of matches) {
|
||||
const fragment = fragmentByMatchId.get(match._id.toString());
|
||||
if (fragment && fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
rebuilt += 1;
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Failed to build match stats fragment for ${match._id.toString()}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return rebuilt;
|
||||
}
|
||||
|
||||
private adjustCardForRange(
|
||||
card: InternalMatchCardView,
|
||||
filteredGames: InternalGameDetail[],
|
||||
): InternalMatchCardView {
|
||||
const allowedGameNumbers = new Set(
|
||||
filteredGames.map((game) => game.gameNumber),
|
||||
);
|
||||
const games = card.games.filter((game) =>
|
||||
allowedGameNumbers.has(game.gameNumber),
|
||||
);
|
||||
const seriesResults = this.rebuildSeriesResults(games);
|
||||
return {
|
||||
...card,
|
||||
games,
|
||||
seriesResults,
|
||||
winnerTeamIndex: this.resolveWinnerTeamIndex(seriesResults),
|
||||
};
|
||||
}
|
||||
|
||||
private rebuildSeriesResults(
|
||||
games: InternalMatchCardView['games'],
|
||||
): InternalMatchCardView['seriesResults'] {
|
||||
const bySeries = new Map<
|
||||
string,
|
||||
InternalMatchCardView['seriesResults'][number]
|
||||
>();
|
||||
|
||||
for (const game of games) {
|
||||
if (game.winnerTeamIndex === null) continue;
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const current = bySeries.get(key) ?? {
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
teamBWins: 0,
|
||||
};
|
||||
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
||||
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
||||
current.winnerTeamIndex =
|
||||
current.teamAWins > current.teamBWins
|
||||
? teamAIndex
|
||||
: current.teamBWins > current.teamAWins
|
||||
? teamBIndex
|
||||
: undefined;
|
||||
bySeries.set(key, current);
|
||||
}
|
||||
|
||||
return [...bySeries.values()].sort(
|
||||
(left, right) =>
|
||||
left.teamAIndex - right.teamAIndex ||
|
||||
left.teamBIndex - right.teamBIndex,
|
||||
);
|
||||
}
|
||||
|
||||
private resolveWinnerTeamIndex(
|
||||
seriesResults: InternalMatchCardView['seriesResults'],
|
||||
): number | undefined {
|
||||
const wins = new Map<number, number>();
|
||||
for (const series of seriesResults) {
|
||||
if (!series.winnerTeamIndex) continue;
|
||||
wins.set(
|
||||
series.winnerTeamIndex,
|
||||
(wins.get(series.winnerTeamIndex) ?? 0) + 1,
|
||||
);
|
||||
}
|
||||
return [...wins.entries()].sort(
|
||||
(left, right) => right[1] - left[1] || left[0] - right[0],
|
||||
)[0]?.[0];
|
||||
}
|
||||
|
||||
private async resolveContext(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
filters: CommunityStatsFilters,
|
||||
): Promise<CommunityStatsContext> {
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const community = await CommunityModel.findById(communityId).exec();
|
||||
if (!community) throw new NotFoundException('Community not found.');
|
||||
const season = this.resolveSeason(community, filters.seasonId);
|
||||
const from = filters.from
|
||||
? new Date(filters.from)
|
||||
: season.startedAt
|
||||
? new Date(season.startedAt)
|
||||
: null;
|
||||
const to = filters.to ? new Date(filters.to) : null;
|
||||
if (from && Number.isNaN(from.getTime())) {
|
||||
throw new BadRequestException('Invalid from date.');
|
||||
}
|
||||
if (to && Number.isNaN(to.getTime())) {
|
||||
throw new BadRequestException('Invalid to date.');
|
||||
}
|
||||
return { community, season, from, to };
|
||||
}
|
||||
|
||||
private resolveSeason(
|
||||
community: CommunityDocument,
|
||||
seasonId?: string,
|
||||
): HistorySeasonDto {
|
||||
const seasons = this.resolveSeasons(community);
|
||||
if (seasonId === 'all') {
|
||||
return { id: 'all', label: '전체 시즌', startedAt: null, endedAt: null };
|
||||
}
|
||||
if (seasonId && seasonId !== 'current') {
|
||||
const selected = seasons.find((season) => season.id === seasonId);
|
||||
if (!selected) throw new BadRequestException('Invalid seasonId.');
|
||||
return selected;
|
||||
}
|
||||
return (
|
||||
seasons.find((season) => !season.endedAt) ??
|
||||
seasons[0] ?? {
|
||||
id: 'current',
|
||||
label: '현재 시즌',
|
||||
startedAt: community.seasonStartedAt?.toISOString() ?? null,
|
||||
endedAt: null,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private resolveSeasons(community: CommunityDocument): HistorySeasonDto[] {
|
||||
const configured = community.seasons?.map((season) => ({
|
||||
id: season.id,
|
||||
label: season.label,
|
||||
startedAt: season.startedAt.toISOString(),
|
||||
endedAt: season.endedAt?.toISOString() ?? null,
|
||||
}));
|
||||
if (configured?.length) return configured;
|
||||
return [
|
||||
{
|
||||
id: 'current',
|
||||
label: '현재 시즌',
|
||||
startedAt: community.seasonStartedAt?.toISOString() ?? null,
|
||||
endedAt: null,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] {
|
||||
const byUser = new Map<string, InternalRecord[]>();
|
||||
for (const record of records) {
|
||||
byUser.set(record.userId, [...(byUser.get(record.userId) ?? []), record]);
|
||||
}
|
||||
return [...byUser.entries()]
|
||||
.map(([userId, rows]) => this.toLeaderboardRow(userId, rows))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.games - left.games || right.winRate - left.winRate,
|
||||
);
|
||||
}
|
||||
|
||||
private toLeaderboardRow(
|
||||
userId: string,
|
||||
records: InternalRecord[],
|
||||
): LeaderboardRow {
|
||||
const first = records[0];
|
||||
const wins = records.filter((record) => record.win).length;
|
||||
const kills = this.sum(records, 'kills');
|
||||
const deaths = this.sum(records, 'deaths');
|
||||
const assists = this.sum(records, 'assists');
|
||||
const byLane: LeaderboardRow['byLane'] = {};
|
||||
for (const lane of [
|
||||
'TOP',
|
||||
'JUNGLE',
|
||||
'MIDDLE',
|
||||
'BOTTOM',
|
||||
'UTILITY',
|
||||
] as RiotLane[]) {
|
||||
const laneRecords = records.filter(
|
||||
(record) => record.teamPosition === lane,
|
||||
);
|
||||
if (laneRecords.length === 0) continue;
|
||||
byLane[lane] = {
|
||||
games: laneRecords.length,
|
||||
wins: laneRecords.filter((record) => record.win).length,
|
||||
kda: this.kda(
|
||||
this.sum(laneRecords, 'kills'),
|
||||
this.sum(laneRecords, 'deaths'),
|
||||
this.sum(laneRecords, 'assists'),
|
||||
),
|
||||
};
|
||||
}
|
||||
const championCounts = new Map<number, { games: number; wins: number }>();
|
||||
for (const record of records) {
|
||||
const current = championCounts.get(record.championId) ?? {
|
||||
games: 0,
|
||||
wins: 0,
|
||||
};
|
||||
current.games += 1;
|
||||
current.wins += record.win ? 1 : 0;
|
||||
championCounts.set(record.championId, current);
|
||||
}
|
||||
|
||||
return {
|
||||
userId,
|
||||
summonerName: first?.summonerName ?? 'Unknown',
|
||||
profileIconId: first?.profileIconId ?? 0,
|
||||
games: records.length,
|
||||
wins,
|
||||
losses: records.length - wins,
|
||||
winRate: this.percent(wins, records.length),
|
||||
totalKills: kills,
|
||||
totalDeaths: deaths,
|
||||
totalAssists: assists,
|
||||
kda: this.kda(kills, deaths, assists),
|
||||
avgGoldPerMin: this.average(this.sum(records, 'gpm'), records.length),
|
||||
avgKillParticipation: this.average(
|
||||
this.sum(records, 'killParticipation'),
|
||||
records.length,
|
||||
),
|
||||
avgCsPerMin: this.average(this.sum(records, 'csPerMin'), records.length),
|
||||
avgDamageShare: this.average(
|
||||
this.sum(records, 'damageShare'),
|
||||
records.length,
|
||||
),
|
||||
avgVisionScore: this.average(
|
||||
this.sum(records, 'visionScore'),
|
||||
records.length,
|
||||
),
|
||||
byLane,
|
||||
topChampions: [...championCounts.entries()]
|
||||
.map(([championId, stat]) => ({
|
||||
championId,
|
||||
games: stat.games,
|
||||
winRate: this.percent(stat.wins, stat.games),
|
||||
}))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.games - left.games || right.winRate - left.winRate,
|
||||
)
|
||||
.slice(0, 3),
|
||||
};
|
||||
}
|
||||
|
||||
private buildUserChampionStats(
|
||||
records: InternalRecord[],
|
||||
season: HistorySeasonDto,
|
||||
): LeaderboardChampionStats {
|
||||
const byChampion = new Map<number, InternalRecord[]>();
|
||||
for (const record of records) {
|
||||
byChampion.set(record.championId, [
|
||||
...(byChampion.get(record.championId) ?? []),
|
||||
record,
|
||||
]);
|
||||
}
|
||||
const champions = [...byChampion.entries()]
|
||||
.map(([championId, rows]) => this.toChampionRow(championId, rows))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.games - left.games || right.winRate - left.winRate,
|
||||
);
|
||||
const totals = this.toChampionRow(0, records);
|
||||
return {
|
||||
queueGroup: 'internal',
|
||||
rank: 'all',
|
||||
queueIds: [],
|
||||
season,
|
||||
lastFetchedAt: records[0]
|
||||
? new Date(records[0].gameCreation).toISOString()
|
||||
: null,
|
||||
champions,
|
||||
totals,
|
||||
};
|
||||
}
|
||||
|
||||
private toChampionRow(championId: number, rows: InternalRecord[]) {
|
||||
const wins = rows.filter((record) => record.win).length;
|
||||
const kills = this.sum(rows, 'kills');
|
||||
const deaths = this.sum(rows, 'deaths');
|
||||
const assists = this.sum(rows, 'assists');
|
||||
const gameMinutes = rows.reduce(
|
||||
(sum, record) => sum + Math.max(record.gameDuration / 60, 1),
|
||||
0,
|
||||
);
|
||||
return {
|
||||
championId,
|
||||
games: rows.length,
|
||||
wins,
|
||||
losses: rows.length - wins,
|
||||
winRate: this.percent(wins, rows.length),
|
||||
avgKills: this.average(kills, rows.length),
|
||||
avgDeaths: this.average(deaths, rows.length),
|
||||
avgAssists: this.average(assists, rows.length),
|
||||
kda: this.kda(kills, deaths, assists),
|
||||
totalKills: kills,
|
||||
totalDeaths: deaths,
|
||||
totalAssists: assists,
|
||||
doubleKills: 0,
|
||||
tripleKills: 0,
|
||||
quadraKills: 0,
|
||||
pentaKills: 0,
|
||||
avgCs: this.average(this.sum(rows, 'cs'), rows.length),
|
||||
avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes),
|
||||
};
|
||||
}
|
||||
|
||||
private buildUserSummary(
|
||||
records: InternalRecord[],
|
||||
requestedLimit: number,
|
||||
): UserInternalHistoryResponse['summary'] {
|
||||
const views = records.slice(0, requestedLimit);
|
||||
const wins = views.filter((record) => record.win).length;
|
||||
const kills = this.sum(views, 'kills');
|
||||
const deaths = this.sum(views, 'deaths');
|
||||
const assists = this.sum(views, 'assists');
|
||||
const best = views.reduce<InternalRecord | null>((bestRecord, record) => {
|
||||
if (!bestRecord) return record;
|
||||
return record.deaths === 0 || record.rating > bestRecord.rating
|
||||
? record
|
||||
: bestRecord;
|
||||
}, null);
|
||||
|
||||
return {
|
||||
windowSize: views.length,
|
||||
winRate: this.percent(wins, views.length),
|
||||
wins,
|
||||
losses: views.length - wins,
|
||||
streak: this.resolveStreak(views),
|
||||
kda: this.kda(kills, deaths, assists),
|
||||
avgKills: this.average(kills, views.length),
|
||||
avgDeaths: this.average(deaths, views.length),
|
||||
avgAssists: this.average(assists, views.length),
|
||||
bestRating: best
|
||||
? {
|
||||
rating: best.deaths === 0 ? 'Perfect' : best.rating,
|
||||
kills: best.kills,
|
||||
deaths: best.deaths,
|
||||
assists: best.assists,
|
||||
matchId: best.riotMatchId,
|
||||
}
|
||||
: null,
|
||||
positionRates: this.resolvePositionRates(views),
|
||||
topChampions: this.resolveTopChampions(views),
|
||||
lastFetchedAt: views[0]
|
||||
? new Date(views[0].gameCreation).toISOString()
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
private toRecentMatchView(
|
||||
record: InternalRecord,
|
||||
dataset: BaseDataset,
|
||||
): RecentMatchView {
|
||||
const detail = dataset.detailsByMatchId
|
||||
.get(record.matchId)
|
||||
?.find((game) => game.riotMatchId === record.riotMatchId);
|
||||
return {
|
||||
matchId: record.riotMatchId,
|
||||
queueId: 0,
|
||||
queueLabel: '내전',
|
||||
gameCreation: record.gameCreation,
|
||||
gameDuration: record.gameDuration,
|
||||
win: record.win,
|
||||
remake: false,
|
||||
championId: record.championId,
|
||||
championLevel: record.championLevel,
|
||||
teamPosition: record.teamPosition,
|
||||
kills: record.kills,
|
||||
deaths: record.deaths,
|
||||
assists: record.assists,
|
||||
kda: this.kda(record.kills, record.deaths, record.assists),
|
||||
rating: record.rating,
|
||||
totalCs: record.cs,
|
||||
csPerMin: record.csPerMin,
|
||||
killParticipation: record.killParticipation,
|
||||
visionScore: record.visionScore,
|
||||
controlWardsBought: record.controlWardsBought,
|
||||
wardsPlaced: record.wardsPlaced,
|
||||
wardsKilled: record.wardsKilled,
|
||||
damageDealtToChampions: record.damageDealtToChampions,
|
||||
damageTaken: record.damageTaken,
|
||||
goldEarned: record.gold,
|
||||
items: record.items,
|
||||
trinket: record.trinket,
|
||||
summonerSpells: record.summonerSpells,
|
||||
perks: record.perks,
|
||||
teams: (detail?.teams ?? []).map((team) => ({
|
||||
side: team.side === 'blue' ? 100 : 200,
|
||||
win: team.win,
|
||||
objectives: team.objectives,
|
||||
participants: team.participants.map((participant) => ({
|
||||
puuid: participant.userId,
|
||||
gameName: participant.summonerName,
|
||||
tagLine: '',
|
||||
championId: participant.championId,
|
||||
championLevel: participant.championLevel,
|
||||
teamPosition: participant.teamPosition,
|
||||
kills: participant.kills,
|
||||
deaths: participant.deaths,
|
||||
assists: participant.assists,
|
||||
items: participant.items,
|
||||
trinket: participant.trinket,
|
||||
summonerSpells: participant.summonerSpells,
|
||||
perks: participant.perks,
|
||||
totalCs: participant.cs,
|
||||
csPerMin: participant.csPerMin,
|
||||
goldEarned: participant.gold,
|
||||
damageDealtToChampions: participant.damageDealtToChampions,
|
||||
damageTaken: participant.damageTaken,
|
||||
visionScore: participant.visionScore,
|
||||
wardsPlaced: participant.wardsPlaced,
|
||||
wardsKilled: participant.wardsKilled,
|
||||
controlWardsBought: participant.controlWardsBought,
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private applyChampionFilter(
|
||||
records: InternalRecord[],
|
||||
filters: CommunityStatsFilters,
|
||||
): InternalRecord[] {
|
||||
if (!filters.championId) return records;
|
||||
return records.filter((record) => record.championId === filters.championId);
|
||||
}
|
||||
|
||||
private isGameInRange(
|
||||
gameCreation: number,
|
||||
context: CommunityStatsContext,
|
||||
): boolean {
|
||||
if (context.from && gameCreation < context.from.getTime()) return false;
|
||||
if (context.to && gameCreation > context.to.getTime()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private toHighlight(
|
||||
row: LeaderboardRow | undefined,
|
||||
field: keyof Pick<
|
||||
LeaderboardRow,
|
||||
'kda' | 'totalKills' | 'avgKillParticipation' | 'avgCsPerMin'
|
||||
>,
|
||||
): LeaderHighlight | null {
|
||||
if (!row) return null;
|
||||
return {
|
||||
metric: Number(row[field]),
|
||||
userId: row.userId,
|
||||
summonerName: row.summonerName,
|
||||
isSingleGame: false,
|
||||
};
|
||||
}
|
||||
|
||||
private toSingleGameHighlight(
|
||||
record: InternalRecord | undefined,
|
||||
field: keyof Pick<InternalRecord, 'gpm'>,
|
||||
): LeaderHighlight | null {
|
||||
if (!record) return null;
|
||||
return {
|
||||
metric: record[field],
|
||||
userId: record.userId,
|
||||
summonerName: record.summonerName,
|
||||
championId: record.championId,
|
||||
matchId: record.riotMatchId,
|
||||
isSingleGame: true,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveStreak(
|
||||
records: InternalRecord[],
|
||||
): UserInternalHistoryResponse['summary']['streak'] {
|
||||
if (records.length === 0) return null;
|
||||
const firstWin = records[0].win;
|
||||
let count = 0;
|
||||
for (const record of records) {
|
||||
if (record.win !== firstWin) break;
|
||||
count += 1;
|
||||
}
|
||||
return { type: firstWin ? 'win' : 'loss', count };
|
||||
}
|
||||
|
||||
private resolvePositionRates(
|
||||
records: InternalRecord[],
|
||||
): Partial<Record<RiotLane, number>> {
|
||||
const counts = new Map<string, number>();
|
||||
for (const record of records) {
|
||||
if (!record.teamPosition) continue;
|
||||
counts.set(
|
||||
record.teamPosition,
|
||||
(counts.get(record.teamPosition) ?? 0) + 1,
|
||||
);
|
||||
}
|
||||
return Object.fromEntries(
|
||||
[...counts.entries()].map(([lane, count]) => [
|
||||
lane,
|
||||
this.percent(count, records.length),
|
||||
]),
|
||||
) as Partial<Record<RiotLane, number>>;
|
||||
}
|
||||
|
||||
private resolveTopChampions(records: InternalRecord[]) {
|
||||
const byChampion = new Map<
|
||||
number,
|
||||
{ games: number; wins: number; rating: number }
|
||||
>();
|
||||
for (const record of records) {
|
||||
const current = byChampion.get(record.championId) ?? {
|
||||
games: 0,
|
||||
wins: 0,
|
||||
rating: 0,
|
||||
};
|
||||
current.games += 1;
|
||||
current.wins += record.win ? 1 : 0;
|
||||
current.rating += record.rating;
|
||||
byChampion.set(record.championId, current);
|
||||
}
|
||||
return [...byChampion.entries()]
|
||||
.map(([championId, stat]) => ({
|
||||
championId,
|
||||
games: stat.games,
|
||||
winRate: this.percent(stat.wins, stat.games),
|
||||
pickRate: this.percent(stat.games, records.length),
|
||||
avgRating: this.average(stat.rating, stat.games),
|
||||
}))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.games - left.games || right.winRate - left.winRate,
|
||||
)
|
||||
.slice(0, 3);
|
||||
}
|
||||
|
||||
private cacheKey(
|
||||
scope: string,
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
filters: CommunityStatsFilters,
|
||||
): string {
|
||||
return [
|
||||
'riot:communitystats',
|
||||
scope,
|
||||
communityId.toString(),
|
||||
filters.seasonId ?? 'current',
|
||||
filters.from ?? '',
|
||||
filters.to ?? '',
|
||||
filters.championId ?? '',
|
||||
filters.cursor ?? '',
|
||||
filters.limit ?? '',
|
||||
].join(':');
|
||||
}
|
||||
|
||||
private clampLimit(
|
||||
value: number | undefined,
|
||||
fallback: number,
|
||||
max: number,
|
||||
): number {
|
||||
if (!value || !Number.isFinite(value)) return fallback;
|
||||
return Math.max(1, Math.min(Math.floor(value), max));
|
||||
}
|
||||
|
||||
private sum<T extends keyof InternalRecord>(
|
||||
records: InternalRecord[],
|
||||
field: T,
|
||||
): number {
|
||||
return records.reduce((total, record) => {
|
||||
const value = record[field];
|
||||
return total + (typeof value === 'number' ? value : 0);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
private kda(kills: number, deaths: number, assists: number): number {
|
||||
return deaths === 0
|
||||
? kills + assists
|
||||
: this.round((kills + assists) / deaths);
|
||||
}
|
||||
|
||||
private percent(value: number, total: number): number {
|
||||
return total > 0 ? Math.round((value / total) * 100) : 0;
|
||||
}
|
||||
|
||||
private average(value: number, total: number): number {
|
||||
return total > 0 ? this.round(value / total) : 0;
|
||||
}
|
||||
|
||||
private round(value: number): number {
|
||||
return Math.round(value * 10) / 10;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user