This commit is contained in:
dahyeon committed 2026-04-26 06:39:00 -07:00
1 parent 60928bc165
commit ca56af79e5
19 files changed
+3450 -21

No files matched your search

+2
View File
@@ -7,6 +7,7 @@ import { AuthModule } from './modules/auth/auth.module';
import { CommunityModule } from './modules/community/community.module';
import { DakaoModule } from './modules/dakao/dakao.module';
import { GlobalModule } from './modules/global/global.module';
import { MatchHistoryModule } from './modules/match-history/match-history.module';
import { MatchModule } from './modules/match/match.module';
import { RiotModule } from './modules/riot/riot.module';
import { UserModule } from './modules/user/user.module';
@@ -22,6 +23,7 @@ import { UserModule } from './modules/user/user.module';
RiotModule,
CommunityModule,
MatchModule,
MatchHistoryModule,
AuctionModule,
UserModule,
DakaoModule,
@@ -176,6 +176,8 @@ export interface RiotAccount extends MongooseTimestamps {
// Riot matchId 참조 (원본은 RiotMatch 컬렉션에 저장)
matchIds: string[];
matchIdsFetchedAt?: Date;
matchIdsByQueueFetchedAt?: Map<string, Date>;
lastRefreshRequestedAt?: Date;
// 최근 경기 요약
recentStatsSummary?: RiotRecentStatsSummary;
@@ -212,6 +214,14 @@ export interface Community extends MongooseTimestamps {
riotPlatform?: RiotPlatformRoute;
riotRegion?: RiotRegionalRoute;
seasonStartedAt?: Date;
seasons?: CommunitySeason[];
}
export interface CommunitySeason {
id: string;
label: string;
startedAt: Date;
endedAt?: Date;
}
export type CommunityDocument = HydratedDocument<Community>;
@@ -468,6 +478,8 @@ const RiotAccountSubSchema = new Schema<RiotAccount>(
matchIds: { type: [String], required: true, default: [] },
matchIdsFetchedAt: { type: Date },
matchIdsByQueueFetchedAt: { type: Map, of: Date },
lastRefreshRequestedAt: { type: Date },
recentStatsSummary: { type: RiotRecentStatsSummarySubSchema },
recentStatsFetchedAt: { type: Date },
@@ -518,6 +530,20 @@ export const CommunitySchema = new Schema<Community>(
riotPlatform: { type: String },
riotRegion: { type: String },
seasonStartedAt: { type: Date },
seasons: {
type: [
new Schema<CommunitySeason>(
{
id: { type: String, required: true },
label: { type: String, required: true },
startedAt: { type: Date, required: true },
endedAt: { type: Date },
},
{ _id: false },
),
],
required: false,
},
},
{
timestamps: true,
@@ -636,6 +662,7 @@ export const RiotMatchSchema = new Schema<RiotMatch>(
);
RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 });
RiotMatchSchema.index({ participantPuuids: 1, queueId: 1, gameCreation: -1 });
const MatchParticipantSubSchema = new Schema<MatchParticipant>(
{
@@ -0,0 +1,95 @@
import { Controller, Get, Param, Query } from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import { MatchHistoryService } from './match-history.service';
@Controller('communities/:communityId/users/:userId')
export class MatchHistoryController {
constructor(private readonly matchHistoryService: MatchHistoryService) {}
@Get('history-profile')
@AllowPublicAccess()
public getProfile(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
) {
return this.matchHistoryService.getProfile({ communityId, userId });
}
@Get('champion-stats')
@AllowPublicAccess()
public getChampionStats(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('queueGroup') queueGroup?: string,
@Query('rank') rank?: string,
@Query('seasonId') seasonId?: string,
) {
return this.matchHistoryService.getChampionStats({
communityId,
userId,
filters: { queueGroup, rank, seasonId },
});
}
@Get('recent-summary')
@AllowPublicAccess()
public getRecentSummary(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('queueGroup') queueGroup?: string,
@Query('rank') rank?: string,
@Query('seasonId') seasonId?: string,
@Query('championId') championId?: string,
@Query('limit') limit?: string,
) {
return this.matchHistoryService.getRecentSummary({
communityId,
userId,
filters: {
queueGroup,
rank,
seasonId,
championId: this.toNumber(championId),
limit: this.toNumber(limit),
},
});
}
@Get('recent-matches')
@AllowPublicAccess()
public getRecentMatches(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('queueGroup') queueGroup?: string,
@Query('rank') rank?: string,
@Query('seasonId') seasonId?: string,
@Query('championId') championId?: string,
@Query('limit') limit?: string,
@Query('cursor') cursor?: string,
) {
return this.matchHistoryService.getRecentMatches({
communityId,
userId,
filters: {
queueGroup,
rank,
seasonId,
championId: this.toNumber(championId),
limit: this.toNumber(limit),
cursor: this.toNumber(cursor),
},
});
}
private toNumber(value: string | undefined): number | undefined {
if (!value) return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { MatchHistoryController } from './match-history.controller';
import { MatchHistoryService } from './match-history.service';
@Module({
controllers: [MatchHistoryController],
providers: [MatchHistoryService],
exports: [MatchHistoryService],
})
export class MatchHistoryModule {}
@@ -0,0 +1,753 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
CommunityDocument,
RiotAccount,
RiotLane,
RiotMatchDocument,
UserDocument,
} from '../global/database/schema';
import {
isRiotQueueGroup,
isRiotRankFilter,
RIOT_QUEUE_LABELS,
resolveRiotQueueIds,
type RiotQueueGroup,
type RiotRankFilter,
} from '../riot/riot-queue.constants';
import type {
RiotMatchDto,
RiotMatchParticipantDto,
} from '../riot/riot.types';
import type {
ChampionStatsResponse,
ChampionStatsRow,
HistorySeasonDto,
RecentMatchesResponse,
RecentMatchView,
RecentSummaryResponse,
UserHistoryProfileResponse,
} from './match-history.types';
const DEFAULT_QUEUE_GROUP: RiotQueueGroup = 'summoners-rift';
const DEFAULT_RANK: RiotRankFilter = 'all';
const DEFAULT_RECENT_LIMIT = 10;
const DEFAULT_SUMMARY_LIMIT = 20;
const MAX_AGGREGATE_MATCHES = 500;
const MAX_RECENT_SCAN = 120;
interface HistoryContext {
community: CommunityDocument;
user: UserDocument;
account: RiotAccount;
season: HistorySeasonDto;
seasonStartedAt: Date | null;
}
interface MatchFilters {
queueGroup?: string;
rank?: string;
seasonId?: string;
championId?: number;
limit?: number;
cursor?: number;
}
interface AggregatedChampion {
championId: number;
games: number;
wins: number;
totalKills: number;
totalDeaths: number;
totalAssists: number;
totalCs: number;
totalGameMinutes: number;
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
}
@Injectable()
export class MatchHistoryService {
constructor(private readonly connectionService: ConnectionService) {}
public async getProfile(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
}): Promise<UserHistoryProfileResponse> {
const context = await this.resolveContext(params);
const lastFetchedAt =
context.account.recentStatsFetchedAt ??
context.account.matchIdsFetchedAt ??
null;
return {
userId: context.user._id.toString(),
puuid: context.account.puuid,
gameName: context.account.gameName,
tagLine: context.account.tagLine,
profileIconId: context.account.profileIconId,
summonerLevel: context.account.summonerLevel,
tiers: context.account.tiers.map((tier) => ({
queueType: tier.queueType,
tier: tier.tier,
rank: tier.rank,
leaguePoints: tier.leaguePoints,
wins: tier.wins,
losses: tier.losses,
fetchedAt: tier.fetchedAt.toISOString(),
})),
season: context.season,
seasons: this.resolveSeasons(context.community),
lastFetchedAt: lastFetchedAt?.toISOString() ?? null,
};
}
public async getChampionStats(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
filters: MatchFilters;
}): Promise<ChampionStatsResponse> {
const context = await this.resolveContext({
...params,
seasonId: params.filters.seasonId,
});
const { queueGroup, rank, queueIds } = this.resolveQueueFilters(
params.filters,
);
const docs = await this.findStoredMatches({
context,
queueIds,
limit: MAX_AGGREGATE_MATCHES,
});
const aggregates = new Map<number, AggregatedChampion>();
for (const doc of docs) {
const dto = doc.raw as unknown as RiotMatchDto;
const participant = this.findParticipant(dto, context.account.puuid);
if (!participant) continue;
const aggregate =
aggregates.get(participant.championId) ??
this.createChampionAggregate(participant.championId);
this.addParticipantToChampionAggregate(aggregate, participant, dto);
aggregates.set(participant.championId, aggregate);
}
const champions = [...aggregates.values()]
.map((aggregate) => this.toChampionStatsRow(aggregate))
.sort((a, b) => b.games - a.games || b.winRate - a.winRate);
const totals = this.toChampionStatsRow(
[...aggregates.values()].reduce(
(acc, aggregate) => this.mergeChampionAggregate(acc, aggregate),
this.createChampionAggregate(0),
),
);
return {
queueGroup,
rank,
queueIds,
season: context.season,
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
champions,
totals,
};
}
public async getRecentSummary(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
filters: MatchFilters;
}): Promise<RecentSummaryResponse> {
const context = await this.resolveContext({
...params,
seasonId: params.filters.seasonId,
});
const { queueIds } = this.resolveQueueFilters(params.filters);
const limit = this.clampLimit(params.filters.limit, DEFAULT_SUMMARY_LIMIT, 50);
const docs = await this.findStoredMatches({
context,
queueIds,
championId: params.filters.championId,
limit,
scanLimit: params.filters.championId ? MAX_RECENT_SCAN : undefined,
});
const views = docs
.map((doc) => this.toRecentMatchView(doc, context.account.puuid))
.filter((view): view is RecentMatchView => Boolean(view))
.slice(0, limit);
return this.createRecentSummary(views, docs, context, limit);
}
public async getRecentMatches(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
filters: MatchFilters;
}): Promise<RecentMatchesResponse> {
const context = await this.resolveContext({
...params,
seasonId: params.filters.seasonId,
});
const { queueIds } = this.resolveQueueFilters(params.filters);
const limit = this.clampLimit(params.filters.limit, DEFAULT_RECENT_LIMIT, 30);
const docs = await this.findStoredMatches({
context,
queueIds,
championId: params.filters.championId,
limit: limit + 1,
cursor: params.filters.cursor,
scanLimit: params.filters.championId ? MAX_RECENT_SCAN : undefined,
});
const views = docs
.map((doc) => this.toRecentMatchView(doc, context.account.puuid))
.filter((view): view is RecentMatchView => Boolean(view));
const page = views.slice(0, limit);
return {
matches: page,
nextCursor: views.length > limit ? page[page.length - 1]?.gameCreation ?? null : null,
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
season: context.season,
};
}
private async resolveContext(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
seasonId?: string;
}): Promise<HistoryContext> {
const UserModel = await this.connectionService.getModel('user');
const CommunityModel = await this.connectionService.getModel('community');
const [user, community] = await Promise.all([
UserModel.findById(params.userId).exec(),
CommunityModel.findById(params.communityId).exec(),
]);
if (!community) throw new NotFoundException('Community not found.');
if (!user || !user.communityId.equals(params.communityId)) {
throw new NotFoundException('User not found.');
}
const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0];
if (!account) {
throw new NotFoundException('Riot account not found.');
}
const season = this.resolveSeason(community, params.seasonId);
const seasonStartedAt = season.startedAt
? new Date(season.startedAt)
: (community.seasonStartedAt ?? null);
return { community, user, account, season, seasonStartedAt };
}
private resolveSeason(
community: CommunityDocument,
seasonId?: string,
): HistorySeasonDto {
const seasons = this.resolveSeasons(community);
if (seasonId && seasonId !== 'current') {
const selected = seasons.find((season) => season.id === seasonId);
if (!selected) throw new BadRequestException('Invalid seasonId.');
return selected;
}
const configured =
seasons.find((season) => !season.endedAt) ??
[...seasons].sort((left, right) =>
(right.startedAt ?? '').localeCompare(left.startedAt ?? ''),
)[0];
if (configured) return configured;
return {
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 resolveQueueFilters(filters: MatchFilters): {
queueGroup: RiotQueueGroup;
rank: RiotRankFilter;
queueIds: number[];
} {
const queueGroup = filters.queueGroup ?? DEFAULT_QUEUE_GROUP;
const rank = filters.rank ?? DEFAULT_RANK;
if (!isRiotQueueGroup(queueGroup)) {
throw new BadRequestException('Invalid queueGroup.');
}
if (!isRiotRankFilter(rank)) {
throw new BadRequestException('Invalid rank filter.');
}
return {
queueGroup,
rank,
queueIds: resolveRiotQueueIds(queueGroup, rank),
};
}
private async findStoredMatches(params: {
context: HistoryContext;
queueIds: number[];
limit: number;
cursor?: number;
championId?: number;
scanLimit?: number;
}): Promise<RiotMatchDocument[]> {
if (params.queueIds.length === 0) return [];
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const gameCreation: Record<string, number> = {};
if (params.context.seasonStartedAt) {
gameCreation.$gte = params.context.seasonStartedAt.getTime();
}
if (params.cursor) gameCreation.$lt = params.cursor;
const query: Record<string, unknown> = {
participantPuuids: params.context.account.puuid,
queueId: { $in: params.queueIds },
};
if (Object.keys(gameCreation).length > 0) query.gameCreation = gameCreation;
const docs = await RiotMatchModel.find(query)
.sort({ gameCreation: -1 })
.limit(params.scanLimit ?? params.limit)
.exec();
if (!params.championId) return docs.slice(0, params.limit);
return docs
.filter((doc) => {
const participant = this.findParticipant(
doc.raw as unknown as RiotMatchDto,
params.context.account.puuid,
);
return participant?.championId === params.championId;
})
.slice(0, params.limit);
}
private findParticipant(
match: RiotMatchDto,
puuid: string,
): RiotMatchParticipantDto | null {
return (
match.info.participants.find((participant) => participant.puuid === puuid) ??
null
);
}
private createChampionAggregate(championId: number): AggregatedChampion {
return {
championId,
games: 0,
wins: 0,
totalKills: 0,
totalDeaths: 0,
totalAssists: 0,
totalCs: 0,
totalGameMinutes: 0,
doubleKills: 0,
tripleKills: 0,
quadraKills: 0,
pentaKills: 0,
};
}
private addParticipantToChampionAggregate(
aggregate: AggregatedChampion,
participant: RiotMatchParticipantDto,
match: RiotMatchDto,
): void {
const minutes = this.resolveGameMinutes(match, participant);
aggregate.games += 1;
aggregate.wins += participant.win ? 1 : 0;
aggregate.totalKills += participant.kills;
aggregate.totalDeaths += participant.deaths;
aggregate.totalAssists += participant.assists;
aggregate.totalCs += this.resolveTotalCs(participant);
aggregate.totalGameMinutes += minutes;
aggregate.doubleKills += this.numberField(participant, 'doubleKills');
aggregate.tripleKills += this.numberField(participant, 'tripleKills');
aggregate.quadraKills += this.numberField(participant, 'quadraKills');
aggregate.pentaKills += this.numberField(participant, 'pentaKills');
}
private mergeChampionAggregate(
acc: AggregatedChampion,
aggregate: AggregatedChampion,
): AggregatedChampion {
acc.games += aggregate.games;
acc.wins += aggregate.wins;
acc.totalKills += aggregate.totalKills;
acc.totalDeaths += aggregate.totalDeaths;
acc.totalAssists += aggregate.totalAssists;
acc.totalCs += aggregate.totalCs;
acc.totalGameMinutes += aggregate.totalGameMinutes;
acc.doubleKills += aggregate.doubleKills;
acc.tripleKills += aggregate.tripleKills;
acc.quadraKills += aggregate.quadraKills;
acc.pentaKills += aggregate.pentaKills;
return acc;
}
private toChampionStatsRow(aggregate: AggregatedChampion): ChampionStatsRow {
const losses = aggregate.games - aggregate.wins;
return {
championId: aggregate.championId,
games: aggregate.games,
wins: aggregate.wins,
losses,
winRate: this.percent(aggregate.wins, aggregate.games),
avgKills: this.average(aggregate.totalKills, aggregate.games),
avgDeaths: this.average(aggregate.totalDeaths, aggregate.games),
avgAssists: this.average(aggregate.totalAssists, aggregate.games),
kda: this.resolveKda(
aggregate.totalKills,
aggregate.totalDeaths,
aggregate.totalAssists,
),
totalKills: aggregate.totalKills,
totalDeaths: aggregate.totalDeaths,
totalAssists: aggregate.totalAssists,
doubleKills: aggregate.doubleKills,
tripleKills: aggregate.tripleKills,
quadraKills: aggregate.quadraKills,
pentaKills: aggregate.pentaKills,
avgCs: this.average(aggregate.totalCs, aggregate.games),
avgCsPerMin: this.average(aggregate.totalCs, aggregate.totalGameMinutes),
};
}
private toRecentMatchView(
doc: RiotMatchDocument,
puuid: string,
): RecentMatchView | null {
const dto = doc.raw as unknown as RiotMatchDto;
const participant = this.findParticipant(dto, puuid);
if (!participant) return null;
const teamParticipants = dto.info.participants.filter(
(candidate) => candidate.teamId === participant.teamId,
);
const teamKills = teamParticipants.reduce(
(sum, candidate) => sum + candidate.kills,
0,
);
const minutes = this.resolveGameMinutes(dto, participant);
const totalCs = this.resolveTotalCs(participant);
const damageShare = this.resolveDamageShare(dto, participant);
const rating = this.resolveRating({
participant,
teamKills,
minutes,
damageShare,
});
return {
matchId: dto.metadata.matchId,
queueId: dto.info.queueId,
queueLabel: RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
win: participant.win,
remake:
this.booleanField(participant, 'gameEndedInEarlySurrender') ||
dto.info.gameDuration < 240,
championId: participant.championId,
championLevel: participant.champLevel,
teamPosition: participant.teamPosition || participant.individualPosition,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
kda: this.resolveKda(
participant.kills,
participant.deaths,
participant.assists,
),
rating,
totalCs,
csPerMin: this.average(totalCs, minutes),
killParticipation: this.percent(
participant.kills + participant.assists,
teamKills,
),
visionScore: participant.visionScore,
controlWardsBought: this.numberField(
participant,
'visionWardsBoughtInGame',
),
wardsPlaced: participant.wardsPlaced,
wardsKilled: participant.wardsKilled,
damageDealtToChampions: participant.totalDamageDealtToChampions,
damageTaken: participant.totalDamageTaken,
goldEarned: participant.goldEarned,
items: [
participant.item0,
participant.item1,
participant.item2,
participant.item3,
participant.item4,
participant.item5,
],
trinket: participant.item6,
summonerSpells: [participant.summoner1Id, participant.summoner2Id],
perks: this.resolvePerks(participant),
teams: this.resolveTeams(dto),
};
}
private createRecentSummary(
views: RecentMatchView[],
docs: RiotMatchDocument[],
context: HistoryContext,
requestedLimit: number,
): RecentSummaryResponse {
const totals = views.reduce(
(acc, view) => {
acc.wins += view.win ? 1 : 0;
acc.kills += view.kills;
acc.deaths += view.deaths;
acc.assists += view.assists;
return acc;
},
{ wins: 0, kills: 0, deaths: 0, assists: 0 },
);
const losses = views.length - totals.wins;
const best = views.reduce<RecentMatchView | null>((acc, view) => {
if (!acc) return view;
return view.deaths === 0 || view.rating > acc.rating ? view : acc;
}, null);
return {
windowSize: Math.min(views.length, requestedLimit),
winRate: this.percent(totals.wins, views.length),
wins: totals.wins,
losses,
streak: this.resolveStreak(views),
kda: this.resolveKda(totals.kills, totals.deaths, totals.assists),
avgKills: this.average(totals.kills, views.length),
avgDeaths: this.average(totals.deaths, views.length),
avgAssists: this.average(totals.assists, views.length),
bestRating: best
? {
rating: best.deaths === 0 ? 'Perfect' : best.rating,
kills: best.kills,
deaths: best.deaths,
assists: best.assists,
matchId: best.matchId,
}
: null,
positionRates: this.resolvePositionRates(views),
topChampions: this.resolveTopChampions(views),
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
};
}
private resolveTeams(match: RiotMatchDto): RecentMatchView['teams'] {
return match.info.teams.map((team) => ({
side: team.teamId as 100 | 200,
win: team.win,
objectives: {
baron: team.objectives?.baron?.kills,
dragon: team.objectives?.dragon?.kills,
tower: team.objectives?.tower?.kills,
},
participants: match.info.participants
.filter((participant) => participant.teamId === team.teamId)
.map((participant) => ({
puuid: participant.puuid,
gameName: participant.riotIdGameName || participant.summonerName || 'Unknown',
tagLine: participant.riotIdTagLine || '',
championId: participant.championId,
teamPosition: participant.teamPosition || participant.individualPosition,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
})),
}));
}
private resolvePerks(participant: RiotMatchParticipantDto): RecentMatchView['perks'] {
const primary = participant.perks.styles.find(
(style) => style.description === 'primaryStyle',
);
const sub = participant.perks.styles.find(
(style) => style.description === 'subStyle',
);
return {
primaryStyle: primary?.style,
subStyle: sub?.style,
keystone: primary?.selections[0]?.perk,
};
}
private resolvePositionRates(
views: RecentMatchView[],
): Partial<Record<RiotLane, number>> {
const counts = new Map<string, number>();
for (const view of views) {
if (!view.teamPosition) continue;
counts.set(view.teamPosition, (counts.get(view.teamPosition) ?? 0) + 1);
}
return Object.fromEntries(
[...counts.entries()].map(([lane, count]) => [
lane,
this.percent(count, views.length),
]),
) as Partial<Record<RiotLane, number>>;
}
private resolveTopChampions(views: RecentMatchView[]): RecentSummaryResponse['topChampions'] {
const byChampion = new Map<number, { games: number; wins: number; rating: number }>();
for (const view of views) {
const stat =
byChampion.get(view.championId) ?? { games: 0, wins: 0, rating: 0 };
stat.games += 1;
stat.wins += view.win ? 1 : 0;
stat.rating += view.rating;
byChampion.set(view.championId, stat);
}
return [...byChampion.entries()]
.map(([championId, stat]) => ({
championId,
games: stat.games,
winRate: this.percent(stat.wins, stat.games),
pickRate: this.percent(stat.games, views.length),
avgRating: this.average(stat.rating, stat.games),
}))
.sort((a, b) => b.games - a.games || b.winRate - a.winRate)
.slice(0, 3);
}
private resolveStreak(
views: RecentMatchView[],
): RecentSummaryResponse['streak'] {
if (views.length === 0) return null;
const firstWin = views[0].win;
let count = 0;
for (const view of views) {
if (view.win !== firstWin) break;
count += 1;
}
return { type: firstWin ? 'win' : 'loss', count };
}
private resolveRating(params: {
participant: RiotMatchParticipantDto;
teamKills: number;
minutes: number;
damageShare: number;
}): number {
const { participant, teamKills, minutes, damageShare } = params;
const kda = this.resolveKda(
participant.kills,
participant.deaths,
participant.assists,
);
const kp = teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0;
const csPerMin = this.resolveTotalCs(participant) / Math.max(minutes, 1);
const visionPerMin = participant.visionScore / Math.max(minutes, 1);
const score =
Math.min(kda / 6, 1) * 4 +
Math.min(kp, 1) * 2 +
Math.min(csPerMin / 9, 1) * 2 +
Math.min(damageShare / 0.35, 1) +
Math.min(visionPerMin / 2, 1);
return this.round(score);
}
private resolveDamageShare(
match: RiotMatchDto,
participant: RiotMatchParticipantDto,
): number {
const teamDamage = match.info.participants
.filter((candidate) => candidate.teamId === participant.teamId)
.reduce((sum, candidate) => sum + candidate.totalDamageDealtToChampions, 0);
return teamDamage > 0 ? participant.totalDamageDealtToChampions / teamDamage : 0;
}
private resolveTotalCs(participant: RiotMatchParticipantDto): number {
return participant.totalMinionsKilled + participant.neutralMinionsKilled;
}
private resolveGameMinutes(
match: RiotMatchDto,
participant: RiotMatchParticipantDto,
): number {
return Math.max((participant.timePlayed || match.info.gameDuration) / 60, 1);
}
private resolveKda(kills: number, deaths: number, assists: number): number {
return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths);
}
private resolveLastFetchedAt(
docs: RiotMatchDocument[],
context: HistoryContext,
): string | null {
if (docs.length === 0) {
return context.account.recentStatsFetchedAt?.toISOString() ?? null;
}
const oldest = docs.reduce((acc, doc) =>
doc.fetchedAt.getTime() < acc.getTime() ? doc.fetchedAt : acc,
docs[0].fetchedAt);
return oldest.toISOString();
}
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 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;
}
private numberField(
value: RiotMatchParticipantDto,
key: string,
): number {
const field = value[key];
return typeof field === 'number' && Number.isFinite(field) ? field : 0;
}
private booleanField(
value: RiotMatchParticipantDto,
key: string,
): boolean {
return value[key] === true;
}
}
@@ -0,0 +1,146 @@
import type { RiotLane } from '../global/database/schema';
import type {
RiotQueueGroup,
RiotRankFilter,
} from '../riot/riot-queue.constants';
export interface HistorySeasonDto {
id: string;
label: string;
startedAt: string | null;
endedAt: string | null;
}
export interface UserHistoryProfileResponse {
userId: string;
puuid: string;
gameName: string;
tagLine: string;
profileIconId: number;
summonerLevel: number;
tiers: Array<{
queueType: string;
tier: string;
rank: string;
leaguePoints: number;
wins: number;
losses: number;
fetchedAt: string;
}>;
season: HistorySeasonDto;
seasons: HistorySeasonDto[];
lastFetchedAt: string | null;
}
export interface ChampionStatsRow {
championId: number;
games: number;
wins: number;
losses: number;
winRate: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
kda: number;
totalKills: number;
totalDeaths: number;
totalAssists: number;
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
avgCs: number;
avgCsPerMin: number;
}
export interface ChampionStatsResponse {
queueGroup: RiotQueueGroup;
rank: RiotRankFilter;
queueIds: number[];
season: HistorySeasonDto;
lastFetchedAt: string | null;
champions: ChampionStatsRow[];
totals: ChampionStatsRow;
}
export interface RecentSummaryResponse {
windowSize: number;
winRate: number;
wins: number;
losses: number;
streak: { type: 'win' | 'loss'; count: number } | null;
kda: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
bestRating: {
rating: number | 'Perfect';
kills: number;
deaths: number;
assists: number;
matchId: string;
} | null;
positionRates: Partial<Record<RiotLane, number>>;
topChampions: Array<{
championId: number;
games: number;
winRate: number;
pickRate: number;
avgRating: number;
}>;
lastFetchedAt: string | null;
}
export interface RecentMatchesResponse {
matches: RecentMatchView[];
nextCursor: number | null;
lastFetchedAt: string | null;
season: HistorySeasonDto;
}
export interface RecentMatchView {
matchId: string;
queueId: number;
queueLabel: string;
gameCreation: number;
gameDuration: number;
win: boolean;
remake: boolean;
championId: number;
championLevel: number;
teamPosition: string;
kills: number;
deaths: number;
assists: number;
kda: number;
rating: number;
totalCs: number;
csPerMin: number;
killParticipation: number;
visionScore: number;
controlWardsBought: number;
wardsPlaced: number;
wardsKilled: number;
damageDealtToChampions: number;
damageTaken: number;
goldEarned: number;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
teams: Array<{
side: 100 | 200;
win: boolean;
objectives?: { baron?: number; dragon?: number; tower?: number };
participants: Array<{
puuid: string;
gameName: string;
tagLine: string;
championId: number;
teamPosition: string;
kills: number;
deaths: number;
assists: number;
}>;
}>;
}
@@ -0,0 +1,88 @@
export type RiotQueueGroup =
| 'all'
| 'summoners-rift'
| 'aram'
| 'urf'
| 'arena';
export type RiotRankFilter = 'all' | 'solo' | 'flex' | 'normal';
export interface RiotQueueGroupConfig {
label: string;
queues: Record<RiotRankFilter, number[]>;
}
export const RIOT_QUEUE_GROUPS: Record<RiotQueueGroup, RiotQueueGroupConfig> = {
all: {
label: '전체',
queues: {
all: [400, 420, 430, 440, 450, 900, 1900, 1700, 1710],
solo: [420],
flex: [440],
normal: [400, 430, 450, 900, 1900, 1700, 1710],
},
},
'summoners-rift': {
label: '소환사의 협곡',
queues: {
all: [400, 420, 430, 440],
solo: [420],
flex: [440],
normal: [400, 430],
},
},
aram: {
label: '칼바람 나락',
queues: {
all: [450],
solo: [],
flex: [],
normal: [450],
},
},
urf: {
label: '우르프',
queues: {
all: [900, 1900],
solo: [],
flex: [],
normal: [900, 1900],
},
},
arena: {
label: '아레나',
queues: {
all: [1700, 1710],
solo: [],
flex: [],
normal: [1700, 1710],
},
},
};
export const RIOT_QUEUE_LABELS: Record<number, string> = {
400: '일반 교차 선택',
420: '솔로 랭크',
430: '일반 비공개 선택',
440: '자유 랭크',
450: '칼바람 나락',
900: '우르프',
1700: '아레나',
1710: '아레나',
1900: '우르프',
};
export function resolveRiotQueueIds(
queueGroup: RiotQueueGroup,
rank: RiotRankFilter,
): number[] {
return RIOT_QUEUE_GROUPS[queueGroup].queues[rank];
}
export function isRiotQueueGroup(value: string): value is RiotQueueGroup {
return value in RIOT_QUEUE_GROUPS;
}
export function isRiotRankFilter(value: string): value is RiotRankFilter {
return value === 'all' || value === 'solo' || value === 'flex' || value === 'normal';
}