feat(api): add match stats fragments
This commit is contained in:
1 parent
b3b59d37fc
commit
956e45ee59
6 files changed
+777
No files matched your search
@@ -0,0 +1,98 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||
|
||||
function makeMatch(): MatchDocument {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
return {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
communityId: new mongoose.Types.ObjectId(),
|
||||
title: '내전',
|
||||
scheduledAt: new Date('2026-05-03T00:00:00.000Z'),
|
||||
status: 'finished',
|
||||
gameCount: 1,
|
||||
participants: [
|
||||
{
|
||||
userId,
|
||||
puuid: 'puuid-1',
|
||||
gameName: 'Player',
|
||||
profileIconId: 7,
|
||||
},
|
||||
],
|
||||
teams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
name: 'A',
|
||||
members: [{ userId, assignedPosition: 'TOP' }],
|
||||
},
|
||||
{ teamIndex: 2, name: 'B', members: [] },
|
||||
],
|
||||
result: {
|
||||
winnerTeamIndex: 1,
|
||||
riotMatchIds: ['KR_1'],
|
||||
games: [
|
||||
{
|
||||
gameNumber: 1,
|
||||
riotMatchId: 'KR_1',
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex: 1,
|
||||
winnerSide: 'blue',
|
||||
gameCreation: 1_000,
|
||||
gameDuration: 1_800,
|
||||
participants: [
|
||||
{
|
||||
userId,
|
||||
teamIndex: 1,
|
||||
side: 'blue',
|
||||
championId: 266,
|
||||
kills: 5,
|
||||
deaths: 1,
|
||||
assists: 7,
|
||||
win: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
seriesResults: [
|
||||
{
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: 1,
|
||||
teamBWins: 0,
|
||||
winnerTeamIndex: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
} as unknown as MatchDocument;
|
||||
}
|
||||
|
||||
describe('MatchStatsFragmentBuilder', () => {
|
||||
it('builds a fallback fragment without raw Riot match data', () => {
|
||||
const builder = new MatchStatsFragmentBuilder();
|
||||
const match = makeMatch();
|
||||
|
||||
const fragment = builder.buildFragment({
|
||||
match,
|
||||
rawByRiotMatchId: new Map(),
|
||||
});
|
||||
|
||||
expect(fragment.matchCard.matchId).toBe(match._id.toString());
|
||||
expect(fragment.gameCreationMin).toBe(1_000);
|
||||
expect(fragment.gameCreationMax).toBe(1_000);
|
||||
expect(fragment.userIds.map((id) => id.toString())).toEqual([
|
||||
match.participants[0].userId.toString(),
|
||||
]);
|
||||
expect(fragment.championIds).toEqual([266]);
|
||||
expect(fragment.records).toHaveLength(1);
|
||||
expect(fragment.records[0]).toMatchObject({
|
||||
summonerName: 'Player',
|
||||
championId: 266,
|
||||
kills: 5,
|
||||
deaths: 1,
|
||||
assists: 7,
|
||||
win: true,
|
||||
});
|
||||
expect(fragment.gameDetails[0].teams[0].participants).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,367 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResultParticipant,
|
||||
TeamSide,
|
||||
} from '../global/database/schema';
|
||||
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
|
||||
import type { InternalMatchCardView } from './community-stats.types';
|
||||
import type {
|
||||
InternalGameDetail,
|
||||
InternalRecord,
|
||||
MatchStatsFragment,
|
||||
} from './match-stats.types';
|
||||
|
||||
@Injectable()
|
||||
export class MatchStatsFragmentBuilder {
|
||||
public buildFragment(params: {
|
||||
match: MatchDocument;
|
||||
rawByRiotMatchId: Map<string, RiotMatchDto>;
|
||||
}): MatchStatsFragment {
|
||||
const games = [...(params.match.result?.games ?? [])].sort(
|
||||
(left, right) => left.gameNumber - right.gameNumber,
|
||||
);
|
||||
const matchCard = this.toMatchCard(params.match, games);
|
||||
const gameDetails = games.map((game) => {
|
||||
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
|
||||
return raw
|
||||
? this.toGameDetail(params.match, game, raw)
|
||||
: this.toFallbackGameDetail(params.match, game);
|
||||
});
|
||||
const records = gameDetails.flatMap((detail) =>
|
||||
detail.teams.flatMap((team) => team.participants),
|
||||
);
|
||||
const gameCreations = gameDetails.map((detail) => detail.gameCreation);
|
||||
|
||||
return {
|
||||
matchCard,
|
||||
records,
|
||||
gameDetails,
|
||||
userIds: [
|
||||
...new Map(
|
||||
records
|
||||
.filter((record) => mongoose.isValidObjectId(record.userId))
|
||||
.map((record) => [
|
||||
record.userId,
|
||||
new mongoose.Types.ObjectId(record.userId),
|
||||
]),
|
||||
).values(),
|
||||
],
|
||||
championIds: [...new Set(records.map((record) => record.championId))],
|
||||
gameCreationMin:
|
||||
gameCreations.length > 0
|
||||
? Math.min(...gameCreations)
|
||||
: params.match.scheduledAt.getTime(),
|
||||
gameCreationMax:
|
||||
gameCreations.length > 0
|
||||
? Math.max(...gameCreations)
|
||||
: params.match.scheduledAt.getTime(),
|
||||
};
|
||||
}
|
||||
|
||||
private toMatchCard(
|
||||
match: MatchDocument,
|
||||
games: NonNullable<MatchDocument['result']>['games'],
|
||||
): InternalMatchCardView {
|
||||
const participantById = new Map(
|
||||
match.participants.map((participant) => [
|
||||
participant.userId.toString(),
|
||||
participant,
|
||||
]),
|
||||
);
|
||||
return {
|
||||
matchId: match._id.toString(),
|
||||
title: match.title,
|
||||
scheduledAt: match.scheduledAt.toISOString(),
|
||||
status: match.status === 'finished' ? 'finished' : 'in-progress',
|
||||
gameCount: match.gameCount,
|
||||
winnerTeamIndex: match.result?.winnerTeamIndex,
|
||||
seriesResults: match.result?.seriesResults ?? [],
|
||||
games: games.map((game) => ({
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId ?? null,
|
||||
blueTeamIndex: game.blueTeamIndex,
|
||||
redTeamIndex: game.redTeamIndex,
|
||||
winnerTeamIndex: game.winnerTeamIndex ?? null,
|
||||
winnerSide: game.winnerSide ?? null,
|
||||
gameDuration: game.gameDuration,
|
||||
})),
|
||||
teams: match.teams.map((team) => ({
|
||||
teamIndex: team.teamIndex,
|
||||
name: team.name,
|
||||
members: team.members.map((member) => {
|
||||
const participant = participantById.get(member.userId.toString());
|
||||
return {
|
||||
userId: member.userId.toString(),
|
||||
summonerName: participant?.gameName ?? 'Unknown',
|
||||
profileIconId: participant?.profileIconId ?? 0,
|
||||
};
|
||||
}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private toGameDetail(
|
||||
match: MatchDocument,
|
||||
game: NonNullable<MatchDocument['result']>['games'][number],
|
||||
raw: RiotMatchDto,
|
||||
): InternalGameDetail {
|
||||
const puuidByUserId = new Map(
|
||||
match.participants
|
||||
.filter((participant) => participant.puuid)
|
||||
.map((participant) => [
|
||||
participant.userId.toString(),
|
||||
participant.puuid as string,
|
||||
]),
|
||||
);
|
||||
const rawByPuuid = new Map(
|
||||
raw.info.participants.map((participant) => [
|
||||
participant.puuid,
|
||||
participant,
|
||||
]),
|
||||
);
|
||||
const rawTeamIdBySide = new Map<TeamSide, number>();
|
||||
for (const participant of game.participants) {
|
||||
const puuid = puuidByUserId.get(participant.userId.toString());
|
||||
const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined;
|
||||
if (rawParticipant) {
|
||||
rawTeamIdBySide.set(participant.side, rawParticipant.teamId);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
winnerSide: game.winnerSide,
|
||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
||||
const teamIndex =
|
||||
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
|
||||
const rawTeamId = rawTeamIdBySide.get(side);
|
||||
const rawTeam = raw.info.teams.find(
|
||||
(team) => team.teamId === rawTeamId,
|
||||
);
|
||||
const teamRawParticipants = raw.info.participants.filter(
|
||||
(participant) => participant.teamId === rawTeamId,
|
||||
);
|
||||
const teamKills = teamRawParticipants.reduce(
|
||||
(sum, participant) => sum + participant.kills,
|
||||
0,
|
||||
);
|
||||
const teamDamage = teamRawParticipants.reduce(
|
||||
(sum, participant) => sum + participant.totalDamageDealtToChampions,
|
||||
0,
|
||||
);
|
||||
return {
|
||||
teamIndex,
|
||||
side,
|
||||
win: game.winnerSide === side,
|
||||
objectives: {
|
||||
baron: rawTeam?.objectives?.baron?.kills ?? 0,
|
||||
dragon: rawTeam?.objectives?.dragon?.kills ?? 0,
|
||||
tower: rawTeam?.objectives?.tower?.kills ?? 0,
|
||||
},
|
||||
participants: game.participants
|
||||
.filter((participant) => participant.side === side)
|
||||
.map((participant) =>
|
||||
this.toRecord({
|
||||
match,
|
||||
game,
|
||||
participant,
|
||||
rawParticipant: rawByPuuid.get(
|
||||
puuidByUserId.get(participant.userId.toString()) ?? '',
|
||||
),
|
||||
teamKills,
|
||||
teamDamage,
|
||||
}),
|
||||
),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
private toFallbackGameDetail(
|
||||
match: MatchDocument,
|
||||
game: NonNullable<MatchDocument['result']>['games'][number],
|
||||
): InternalGameDetail {
|
||||
return {
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
winnerSide: game.winnerSide,
|
||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
||||
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
||||
side,
|
||||
win: game.winnerSide === side,
|
||||
objectives: { baron: 0, dragon: 0, tower: 0 },
|
||||
participants: game.participants
|
||||
.filter((participant) => participant.side === side)
|
||||
.map((participant) =>
|
||||
this.toRecord({
|
||||
match,
|
||||
game,
|
||||
participant,
|
||||
teamKills: 0,
|
||||
teamDamage: 0,
|
||||
}),
|
||||
),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private toRecord(params: {
|
||||
match: MatchDocument;
|
||||
game: NonNullable<MatchDocument['result']>['games'][number];
|
||||
participant: MatchGameResultParticipant;
|
||||
rawParticipant?: RiotMatchParticipantDto;
|
||||
teamKills: number;
|
||||
teamDamage: number;
|
||||
}): InternalRecord {
|
||||
const { match, game, participant, rawParticipant, teamKills, teamDamage } =
|
||||
params;
|
||||
const snapshot = match.participants.find((item) =>
|
||||
item.userId.equals(participant.userId),
|
||||
);
|
||||
const minutes = Math.max(
|
||||
(rawParticipant?.timePlayed ?? game.gameDuration) / 60,
|
||||
1,
|
||||
);
|
||||
const cs = rawParticipant
|
||||
? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled
|
||||
: 0;
|
||||
const damage = rawParticipant?.totalDamageDealtToChampions ?? 0;
|
||||
const killParticipation = percent(
|
||||
participant.kills + participant.assists,
|
||||
teamKills,
|
||||
);
|
||||
const damageShare = percent(damage, teamDamage);
|
||||
const rating = this.resolveRating({
|
||||
kills: participant.kills,
|
||||
deaths: participant.deaths,
|
||||
assists: participant.assists,
|
||||
killParticipation,
|
||||
csPerMin: average(cs, minutes),
|
||||
damageShare,
|
||||
visionPerMin: average(rawParticipant?.visionScore ?? 0, minutes),
|
||||
});
|
||||
|
||||
return {
|
||||
matchId: match._id.toString(),
|
||||
title: match.title,
|
||||
scheduledAt: match.scheduledAt,
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
userId: participant.userId.toString(),
|
||||
summonerName:
|
||||
snapshot?.gameName ??
|
||||
rawParticipant?.riotIdGameName ??
|
||||
rawParticipant?.summonerName ??
|
||||
'Unknown',
|
||||
profileIconId: snapshot?.profileIconId ?? 0,
|
||||
teamIndex: participant.teamIndex,
|
||||
side: participant.side,
|
||||
championId: participant.championId,
|
||||
championLevel: rawParticipant?.champLevel ?? 0,
|
||||
teamPosition:
|
||||
rawParticipant?.teamPosition ||
|
||||
rawParticipant?.individualPosition ||
|
||||
'',
|
||||
kills: participant.kills,
|
||||
deaths: participant.deaths,
|
||||
assists: participant.assists,
|
||||
win: participant.win,
|
||||
cs,
|
||||
csPerMin: average(cs, minutes),
|
||||
gold: rawParticipant?.goldEarned ?? 0,
|
||||
gpm: average(rawParticipant?.goldEarned ?? 0, minutes),
|
||||
damageDealtToChampions: damage,
|
||||
damageTaken: rawParticipant?.totalDamageTaken ?? 0,
|
||||
damageShare,
|
||||
killParticipation,
|
||||
visionScore: rawParticipant?.visionScore ?? 0,
|
||||
controlWardsBought: numberField(
|
||||
rawParticipant,
|
||||
'visionWardsBoughtInGame',
|
||||
),
|
||||
wardsPlaced: rawParticipant?.wardsPlaced ?? 0,
|
||||
wardsKilled: rawParticipant?.wardsKilled ?? 0,
|
||||
items: [
|
||||
rawParticipant?.item0 ?? 0,
|
||||
rawParticipant?.item1 ?? 0,
|
||||
rawParticipant?.item2 ?? 0,
|
||||
rawParticipant?.item3 ?? 0,
|
||||
rawParticipant?.item4 ?? 0,
|
||||
rawParticipant?.item5 ?? 0,
|
||||
],
|
||||
trinket: rawParticipant?.item6 ?? 0,
|
||||
summonerSpells: [
|
||||
rawParticipant?.summoner1Id ?? 0,
|
||||
rawParticipant?.summoner2Id ?? 0,
|
||||
],
|
||||
perks: rawParticipant ? this.resolvePerks(rawParticipant) : {},
|
||||
rating,
|
||||
};
|
||||
}
|
||||
|
||||
private resolvePerks(participant: RiotMatchParticipantDto) {
|
||||
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 resolveRating(params: {
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
killParticipation: number;
|
||||
csPerMin: number;
|
||||
damageShare: number;
|
||||
visionPerMin: number;
|
||||
}): number {
|
||||
const kdaScore = kda(params.kills, params.deaths, params.assists);
|
||||
const score =
|
||||
Math.min(kdaScore / 6, 1) * 4 +
|
||||
Math.min(params.killParticipation / 100, 1) * 2 +
|
||||
Math.min(params.csPerMin / 9, 1) * 2 +
|
||||
Math.min(params.damageShare / 35, 1) +
|
||||
Math.min(params.visionPerMin / 2, 1);
|
||||
return round(score);
|
||||
}
|
||||
}
|
||||
|
||||
function kda(kills: number, deaths: number, assists: number): number {
|
||||
return deaths === 0 ? kills + assists : round((kills + assists) / deaths);
|
||||
}
|
||||
|
||||
function percent(value: number, total: number): number {
|
||||
return total > 0 ? Math.round((value / total) * 100) : 0;
|
||||
}
|
||||
|
||||
function average(value: number, total: number): number {
|
||||
return total > 0 ? round(value / total) : 0;
|
||||
}
|
||||
|
||||
function round(value: number): number {
|
||||
return Math.round(value * 10) / 10;
|
||||
}
|
||||
|
||||
function numberField(
|
||||
participant: RiotMatchParticipantDto | undefined,
|
||||
key: string,
|
||||
): number {
|
||||
const value = participant?.[key];
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
|
||||
|
||||
@Injectable()
|
||||
export class MatchStatsRepository {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async upsert(
|
||||
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
|
||||
): Promise<void> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
await MatchStatsModel.updateOne(
|
||||
{ matchId: fragment.matchId },
|
||||
{ $set: fragment },
|
||||
{ upsert: true },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
await MatchStatsModel.deleteOne({ matchId }).exec();
|
||||
}
|
||||
|
||||
public async deleteByMatches(
|
||||
matchIds: mongoose.Types.ObjectId[],
|
||||
): Promise<void> {
|
||||
if (matchIds.length === 0) return;
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec();
|
||||
}
|
||||
|
||||
public async findByMatch(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<MatchStatsDocument | null> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
return MatchStatsModel.findOne({ matchId }).exec();
|
||||
}
|
||||
|
||||
public async findByCommunity(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
fromGameCreation?: number;
|
||||
toGameCreation?: number;
|
||||
limit?: number;
|
||||
}): Promise<MatchStatsDocument[]> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
const filter: Record<string, unknown> = {
|
||||
communityId: params.communityId,
|
||||
};
|
||||
if (params.fromGameCreation !== undefined) {
|
||||
filter.gameCreationMax = { $gte: params.fromGameCreation };
|
||||
}
|
||||
if (params.toGameCreation !== undefined) {
|
||||
filter.gameCreationMin = { $lte: params.toGameCreation };
|
||||
}
|
||||
|
||||
return MatchStatsModel.find(filter)
|
||||
.sort({ scheduledAt: -1 })
|
||||
.limit(params.limit ?? 300)
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async findByUser(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
fromGameCreation?: number;
|
||||
toGameCreation?: number;
|
||||
}): Promise<MatchStatsDocument[]> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
const filter: Record<string, unknown> = {
|
||||
communityId: params.communityId,
|
||||
userIds: params.userId,
|
||||
};
|
||||
if (params.fromGameCreation !== undefined) {
|
||||
filter.gameCreationMax = { $gte: params.fromGameCreation };
|
||||
}
|
||||
if (params.toGameCreation !== undefined) {
|
||||
filter.gameCreationMin = { $lte: params.toGameCreation };
|
||||
}
|
||||
|
||||
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
import { MatchStatsService } from './match-stats.service';
|
||||
|
||||
describe('MatchStatsService', () => {
|
||||
it('deletes an existing fragment when the match is no longer eligible', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const findById = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
_id: matchId,
|
||||
status: 'recruiting',
|
||||
result: undefined,
|
||||
}),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'match') return { findById };
|
||||
if (name === 'riotMatch') return {};
|
||||
throw new Error(`Unexpected model: ${name}`);
|
||||
}),
|
||||
} as unknown as ConnectionService;
|
||||
const repository = {
|
||||
deleteByMatch: jest.fn().mockResolvedValue(undefined),
|
||||
upsert: jest.fn(),
|
||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||
const service = new MatchStatsService(
|
||||
connectionService,
|
||||
repository,
|
||||
{} as MatchStatsFragmentBuilder,
|
||||
);
|
||||
|
||||
await service.buildAndUpsert(matchId);
|
||||
|
||||
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId);
|
||||
expect(repository.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('upserts a fragment for eligible matches', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const scheduledAt = new Date('2026-05-03T00:00:00.000Z');
|
||||
const match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
scheduledAt,
|
||||
status: 'finished',
|
||||
result: { games: [{ riotMatchId: 'KR_1' }] },
|
||||
};
|
||||
const findById = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(match),
|
||||
});
|
||||
const riotFind = jest.fn().mockReturnValue({
|
||||
lean: () => ({
|
||||
exec: jest.fn().mockResolvedValue([{ matchId: 'KR_1', raw: {} }]),
|
||||
}),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'match') return { findById };
|
||||
if (name === 'riotMatch') return { find: riotFind };
|
||||
throw new Error(`Unexpected model: ${name}`);
|
||||
}),
|
||||
} as unknown as ConnectionService;
|
||||
const repository = {
|
||||
upsert: jest.fn().mockResolvedValue(undefined),
|
||||
deleteByMatch: jest.fn(),
|
||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||
const builder = {
|
||||
buildFragment: jest.fn().mockReturnValue({
|
||||
matchCard: { matchId: matchId.toString() },
|
||||
records: [],
|
||||
gameDetails: [],
|
||||
userIds: [],
|
||||
championIds: [],
|
||||
gameCreationMin: 1_000,
|
||||
gameCreationMax: 2_000,
|
||||
}),
|
||||
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
|
||||
const service = new MatchStatsService(
|
||||
connectionService,
|
||||
repository,
|
||||
builder,
|
||||
);
|
||||
|
||||
await service.buildAndUpsert(matchId);
|
||||
|
||||
expect(builder.buildFragment).toHaveBeenCalledWith({
|
||||
match,
|
||||
rawByRiotMatchId: expect.any(Map),
|
||||
});
|
||||
expect(repository.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
matchId,
|
||||
communityId,
|
||||
scheduledAt,
|
||||
gameCreationMin: 1_000,
|
||||
gameCreationMax: 2_000,
|
||||
builderVersion: 1,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
import type { RiotMatchDto } from '../riot/riot.types';
|
||||
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
|
||||
|
||||
@Injectable()
|
||||
export class MatchStatsService {
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly repository: MatchStatsRepository,
|
||||
private readonly builder: MatchStatsFragmentBuilder,
|
||||
) {}
|
||||
|
||||
public async buildAndUpsert(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const match = await MatchModel.findById(matchId).exec();
|
||||
if (!match) return;
|
||||
if (!this.isEligible(match)) {
|
||||
await this.repository.deleteByMatch(matchId);
|
||||
return;
|
||||
}
|
||||
|
||||
const riotIds = [
|
||||
...new Set(
|
||||
(match.result?.games ?? [])
|
||||
.map((game) => game.riotMatchId)
|
||||
.filter((riotMatchId): riotMatchId is string => Boolean(riotMatchId)),
|
||||
),
|
||||
];
|
||||
const riotDocs =
|
||||
riotIds.length > 0
|
||||
? await RiotMatchModel.find({ matchId: { $in: riotIds } })
|
||||
.lean()
|
||||
.exec()
|
||||
: [];
|
||||
const rawByRiotMatchId = new Map(
|
||||
riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
|
||||
);
|
||||
const fragment = this.builder.buildFragment({ match, rawByRiotMatchId });
|
||||
|
||||
await this.repository.upsert({
|
||||
matchId: match._id,
|
||||
communityId: match.communityId,
|
||||
scheduledAt: match.scheduledAt,
|
||||
gameCreationMin: fragment.gameCreationMin,
|
||||
gameCreationMax: fragment.gameCreationMax,
|
||||
userIds: fragment.userIds,
|
||||
championIds: fragment.championIds,
|
||||
matchCard: fragment.matchCard as unknown as Record<string, unknown>,
|
||||
records: fragment.records,
|
||||
gameDetails: fragment.gameDetails,
|
||||
builtAt: new Date(),
|
||||
builderVersion: MATCH_STATS_BUILDER_VERSION,
|
||||
});
|
||||
}
|
||||
|
||||
public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||
await this.repository.deleteByMatch(matchId);
|
||||
}
|
||||
|
||||
public async removeByMatches(
|
||||
matchIds: mongoose.Types.ObjectId[],
|
||||
): Promise<void> {
|
||||
await this.repository.deleteByMatches(matchIds);
|
||||
}
|
||||
|
||||
public async backfillCommunity(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<{ processed: number; failed: number }> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const matches = await MatchModel.find({
|
||||
communityId,
|
||||
status: { $in: ['finished', 'in-progress'] },
|
||||
'result.games.0': { $exists: true },
|
||||
})
|
||||
.sort({ scheduledAt: -1 })
|
||||
.select({ _id: 1 })
|
||||
.exec();
|
||||
|
||||
let processed = 0;
|
||||
let failed = 0;
|
||||
for (const match of matches) {
|
||||
try {
|
||||
await this.buildAndUpsert(match._id);
|
||||
processed += 1;
|
||||
} catch {
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
return { processed, failed };
|
||||
}
|
||||
|
||||
private isEligible(match: MatchDocument): boolean {
|
||||
return (
|
||||
(match.status === 'finished' || match.status === 'in-progress') &&
|
||||
Boolean(match.result?.games?.length)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type {
|
||||
MatchStatsGameDetail,
|
||||
MatchStatsRecord,
|
||||
} from '../global/database/schema';
|
||||
import type { InternalMatchCardView } from './community-stats.types';
|
||||
|
||||
export const MATCH_STATS_BUILDER_VERSION = 1;
|
||||
|
||||
export type InternalRecord = MatchStatsRecord;
|
||||
export type InternalGameDetail = MatchStatsGameDetail;
|
||||
|
||||
export interface MatchStatsFragment {
|
||||
matchCard: InternalMatchCardView;
|
||||
records: InternalRecord[];
|
||||
gameDetails: InternalGameDetail[];
|
||||
userIds: import('mongoose').Types.ObjectId[];
|
||||
championIds: number[];
|
||||
gameCreationMin: number;
|
||||
gameCreationMax: number;
|
||||
}
|
||||
Reference in new issue
Block a user