feat(api): add match management

This commit is contained in:
dahyeon committed 2026-04-13 02:40:00 +09:00
1 parent 6cd213a462
commit 87447a4f09
6 files changed
+1929

No files matched your search

@@ -0,0 +1,187 @@
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
ArrayMinSize,
registerDecorator,
IsArray,
IsDate,
IsEnum,
IsInt,
IsOptional,
IsString,
MaxLength,
Min,
MinLength,
ValidateNested,
ValidationArguments,
ValidationOptions,
} from 'class-validator';
import { MATCH_GAME_MODES, POSITIONS } from '../../global/database/schema';
import type { MatchGameMode, Position } from '../../global/database/schema';
function IsMultipleOf(
multiple: number,
validationOptions?: ValidationOptions,
): PropertyDecorator {
return (object, propertyName) => {
registerDecorator({
name: 'isMultipleOf',
target: object.constructor,
propertyName: String(propertyName),
constraints: [multiple],
options: validationOptions,
validator: {
validate(value: unknown, args: ValidationArguments) {
const [divisor] = args.constraints as [number];
return (
typeof value === 'number' &&
Number.isInteger(value) &&
value % divisor === 0
);
},
defaultMessage(args: ValidationArguments) {
const [divisor] = args.constraints as [number];
return `${args.property} must be a multiple of ${divisor}.`;
},
},
});
};
}
export class PositionPreferenceDto {
@IsEnum(POSITIONS)
position!: Position;
@IsInt()
@Min(1)
priority!: number;
}
class MatchScheduleItemDto {
@IsString()
@MaxLength(32)
time!: string;
@IsString()
@MaxLength(128)
label!: string;
}
export class CreateMatchDto {
@IsString()
@MinLength(1)
@MaxLength(128)
title!: string;
@IsOptional()
@IsString()
@MaxLength(2048)
description?: string;
@IsOptional()
@IsInt()
mapId?: number;
@IsDate()
@Type(() => Date)
scheduledAt!: Date;
@IsOptional()
@IsInt()
@Min(10)
@IsMultipleOf(10)
maxParticipants?: number;
@IsOptional()
@IsInt()
@Min(1)
gameCount?: number;
@IsOptional()
@IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode;
@IsOptional()
@IsArray()
@IsString({ each: true })
@ArrayMaxSize(32)
prizes?: string[];
@IsOptional()
@IsArray()
@IsString({ each: true })
@ArrayMaxSize(32)
notices?: string[];
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => MatchScheduleItemDto)
@ArrayMaxSize(32)
schedule?: MatchScheduleItemDto[];
}
export class UpdateMatchDto {
@IsOptional()
@IsString()
@MaxLength(128)
title?: string;
@IsOptional()
@IsString()
@MaxLength(2048)
description?: string;
@IsOptional()
@IsInt()
mapId?: number;
@IsOptional()
@IsDate()
@Type(() => Date)
scheduledAt?: Date;
@IsOptional()
@IsInt()
@Min(10)
@IsMultipleOf(10)
maxParticipants?: number;
@IsOptional()
@IsInt()
@Min(1)
gameCount?: number;
@IsOptional()
@IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode;
@IsOptional()
@IsArray()
@IsString({ each: true })
prizes?: string[];
@IsOptional()
@IsArray()
@IsString({ each: true })
notices?: string[];
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => MatchScheduleItemDto)
schedule?: MatchScheduleItemDto[];
}
export class JoinMatchDto {
@IsArray()
@ArrayMinSize(1)
@ArrayMaxSize(5)
@ValidateNested({ each: true })
@Type(() => PositionPreferenceDto)
preferredPositions!: PositionPreferenceDto[];
@IsOptional()
@IsString()
userId?: string;
}
@@ -0,0 +1,170 @@
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type {
MatchDocument,
MatchStatus,
UserDocument,
} from '../global/database/schema';
import {
CreateMatchDto,
JoinMatchDto,
UpdateMatchDto,
} from './dto/create-match.dto';
import { MatchService } from './match.service';
@Controller('communities/:communityId/matches')
export class MatchController {
constructor(private readonly matchService: MatchService) {}
@Post()
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async createMatch(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Body() body: CreateMatchDto,
) {
this.assertSameCommunity(currentUser, communityId);
return this.matchService.create({
communityId,
hostUserId: currentUser._id,
data: {
title: body.title,
description: body.description ?? '',
mapId: body.mapId ?? 11,
scheduledAt: body.scheduledAt,
maxParticipants: body.maxParticipants ?? 10,
gameCount: body.gameCount,
gameMode: body.gameMode ?? 'pair',
prizes: body.prizes ?? [],
notices: body.notices ?? [],
schedule: body.schedule ?? [],
},
});
}
// 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환.
@Get()
@AllowPublicAccess()
public async listMatches(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('status') status?: MatchStatus,
@Query('limit') limit?: string,
) {
const matches = await this.matchService.list({
communityId,
status,
limit: limit ? Number(limit) : undefined,
});
if (!currentUser) return { matches };
const myId = currentUser._id;
return {
matches: matches.map((m) => this.annotateJoined(m, myId)),
};
}
@Get(':matchId')
@AllowPublicAccess()
public async getMatch(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
const match = await this.matchService.getById(matchId);
return this.matchService.serialize(match);
}
@Patch(':matchId')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async updateMatch(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: UpdateMatchDto,
) {
this.assertSameCommunity(currentUser, communityId);
return this.matchService.update({ matchId, communityId, patch: body });
}
@Delete(':matchId')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
@HttpCode(HttpStatus.NO_CONTENT)
public async deleteMatch(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
this.assertSameCommunity(currentUser, communityId);
await this.matchService.remove({ matchId, communityId });
}
// 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용).
@Post(':matchId/participants')
@AllowPublicAccess()
public async joinMatch(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: JoinMatchDto,
) {
const userId = this.resolveJoinerUserId(currentUser, body.userId);
return this.matchService.join({
matchId,
userId,
preferredPositions: body.preferredPositions,
});
}
private resolveJoinerUserId(
currentUser: UserDocument | undefined,
bodyUserId?: string,
): mongoose.Types.ObjectId {
if (currentUser) return currentUser._id;
if (!bodyUserId || !mongoose.isValidObjectId(bodyUserId)) {
throw new BadRequestException(
'userId is required when not authenticated.',
);
}
return new mongoose.Types.ObjectId(bodyUserId);
}
private annotateJoined(
match: MatchDocument,
userId: mongoose.Types.ObjectId,
) {
const obj = match.toObject();
const joined = match.participants.some((p) => p.userId.equals(userId));
return { ...obj, joined };
}
private assertSameCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!user.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { TournamentCodeModule } from '../tournament-code/tournament-code.module';
import { MatchController } from './match.controller';
import { MatchService } from './match.service';
@Module({
imports: [TournamentCodeModule, CommunityStatsModule],
controllers: [MatchController],
providers: [MatchService],
exports: [MatchService],
})
export class MatchModule {}
@@ -0,0 +1,105 @@
import mongoose from 'mongoose';
import { MatchService } from './match.service';
describe('MatchService', () => {
function createService(match: Record<string, unknown>) {
const MatchModel = {
findById: jest.fn().mockResolvedValue(match),
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return MatchModel;
return {};
}),
};
const tournamentCodeService = {
buildSlots: jest.fn().mockResolvedValue([]),
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
};
const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
};
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
removeByMatch: jest.fn().mockResolvedValue(undefined),
};
return {
service: new MatchService(
connectionService as never,
tournamentCodeService as never,
communityStatsService as never,
matchStatsService as never,
),
tournamentCodeService,
matchStatsService,
};
}
it('clears game schedule when a built match returns to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
status: 'team-built',
tournamentCodeIds: [],
gameSchedule: [{ gameNumber: 1, teamAIndex: 2, teamBIndex: 4 }],
teams: [{ teamIndex: 1 }],
teamBuiltAt: new Date(),
result: { games: [] },
resultPollState: { state: 'polling' },
set: jest.fn(function (
this: Record<string, unknown>,
patch: Record<string, unknown>,
) {
Object.assign(this, patch);
}),
save: jest.fn().mockResolvedValue(undefined),
};
const { service, tournamentCodeService, matchStatsService } =
createService(match);
await service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
});
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
expect(match.tournamentCodeIds).toEqual([]);
expect(match.gameSchedule).toEqual([]);
expect(match.teamBuiltAt).toBeUndefined();
expect(match.result).toBeUndefined();
expect(match.resultPollState).toBeUndefined();
expect(match.save).toHaveBeenCalledTimes(1);
expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id);
});
it('releases reserved codes when returning a built match to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const codeId = new mongoose.Types.ObjectId();
const match = {
communityId,
status: 'in-progress',
tournamentCodeIds: [codeId],
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 3 }],
set: jest.fn(function (
this: Record<string, unknown>,
patch: Record<string, unknown>,
) {
Object.assign(this, patch);
}),
save: jest.fn().mockResolvedValue(undefined),
};
const { service, tournamentCodeService } = createService(match);
await service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
});
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match);
expect(match.tournamentCodeIds).toEqual([]);
expect(match.gameSchedule).toEqual([]);
});
});
+360
View File
@@ -0,0 +1,360 @@
import {
BadRequestException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import {
Match,
MatchDocument,
MatchSeriesResult,
MatchStatus,
PositionPreference,
TierInfo,
} from '../global/database/schema';
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const MATCH_SHORT_CODE_LENGTH = 4;
const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
interface CreateMatchParams {
communityId: mongoose.Types.ObjectId;
hostUserId?: mongoose.Types.ObjectId;
data: Partial<Match> & Pick<Match, 'title' | 'scheduledAt'>;
}
interface UpdateMatchParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
patch: Partial<Match>;
}
interface ListMatchesQuery {
communityId: mongoose.Types.ObjectId;
status?: MatchStatus;
limit?: number;
}
interface JoinMatchParams {
matchId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
preferredPositions: PositionPreference[];
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
riotPuuid?: string;
}
interface CancelMatchJoinParams {
matchId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
}
@Injectable()
export class MatchService {
constructor(
private readonly connectionService: ConnectionService,
private readonly tournamentCodeService: TournamentCodeService,
private readonly communityStatsService: CommunityStatsService,
private readonly matchStatsService: MatchStatsService,
) {}
public async create(params: CreateMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(params.communityId)
.select({ matchGameCount: 1 })
.lean()
.exec();
return MatchModel.create({
...params.data,
shortCode:
params.data.shortCode ??
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
gameCount:
params.data.gameCount ??
community?.matchGameCount ??
DEFAULT_TOURNAMENT_GAME_COUNT,
communityId: params.communityId,
hostUserId: params.hostUserId,
});
}
public async list(query: ListMatchesQuery): Promise<MatchDocument[]> {
const MatchModel = await this.connectionService.getModel('match');
const filter: {
communityId: mongoose.Types.ObjectId;
status?: MatchStatus;
} = {
communityId: query.communityId,
};
if (query.status) filter.status = query.status;
return MatchModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(Math.min(query.limit ?? 50, 200))
.exec();
}
public async ensureShortCode(match: MatchDocument): Promise<MatchDocument> {
if (match.shortCode) return match;
const MatchModel = await this.connectionService.getModel('match');
match.shortCode = await this.generateUniqueShortCode(
MatchModel,
match.communityId,
);
await match.save();
return match;
}
public async getById(
matchId: mongoose.Types.ObjectId,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId);
if (!match) throw new NotFoundException('Match not found.');
return match;
}
public async serialize(match: MatchDocument) {
const obj = match.toObject();
if (obj.result?.games) {
obj.result.games = [...obj.result.games].sort(
(left, right) => left.gameNumber - right.gameNumber,
);
if (!obj.result.seriesResults?.length) {
obj.result.seriesResults = this.buildSeriesResults(obj.result.games);
}
}
return {
...obj,
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
gameMode: match.gameMode ?? 'pair',
participants: (obj.participants ?? []).map((participant) => ({
...participant,
excluded: participant.excluded ?? false,
})),
teams: (obj.teams ?? []).map((team) => ({
...team,
})),
gameSchedule: obj.gameSchedule ?? [],
tournamentCodes: await this.tournamentCodeService.buildSlots(match),
};
}
public async update(params: UpdateMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
const previousStatus = match.status;
if (
previousStatus !== 'recruiting' &&
('maxParticipants' in params.patch || 'gameMode' in params.patch)
) {
throw new BadRequestException(
'maxParticipants and gameMode can only be changed while recruiting.',
);
}
match.set(params.patch);
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
if (match.tournamentCodeIds.length > 0) {
await this.tournamentCodeService.releaseFromMatch(match);
}
match.tournamentCodeIds = [];
match.gameSchedule = [];
match.teamBuiltAt = undefined;
match.result = undefined;
match.resultPollState = undefined;
}
await match.save();
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
await this.matchStatsService.removeByMatch(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId);
} else if (match.result?.games?.length) {
await this.matchStatsService.buildAndUpsert(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId);
}
return match;
}
public async remove(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
}): Promise<void> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
await this.tournamentCodeService.releaseFromMatch(match);
await this.matchStatsService.removeByMatch(match._id);
await match.deleteOne();
await this.communityStatsService.invalidateCommunity(params.communityId);
}
public async join(params: JoinMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.userId);
if (!user) throw new NotFoundException('User not found.');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
if (match.participants.length >= match.maxParticipants) {
throw new BadRequestException('Match is full.');
}
const alreadyIn = match.participants.some((p) => p.userId.equals(user._id));
if (alreadyIn) {
throw new BadRequestException('User already joined this match.');
}
const selectedRiot = params.riotPuuid
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
: user.riotAccounts.find((a) => a.isPrimary);
const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []);
match.participants.push({
userId: user._id,
puuid: selectedRiot?.puuid,
gameName: selectedRiot?.gameName,
tagLine: selectedRiot?.tagLine,
profileIconId: selectedRiot?.profileIconId,
tier: selectedTier,
preferredPositions: params.preferredPositions,
joinedAt: new Date(),
excluded: false,
});
await match.save();
return match;
}
public async cancelJoin(
params: CancelMatchJoinParams,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.userId);
if (!user) throw new NotFoundException('User not found.');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
const participantIndex = match.participants.findIndex((participant) =>
participant.userId.equals(user._id),
);
if (participantIndex === -1) {
throw new BadRequestException('User has not joined this match.');
}
match.participants.splice(participantIndex, 1);
await match.save();
return match;
}
private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined {
const tier =
tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0];
if (!tier) return undefined;
return {
leagueId: tier.leagueId,
queueType: tier.queueType,
tier: tier.tier,
rank: tier.rank,
puuid: tier.puuid,
leaguePoints: tier.leaguePoints,
wins: tier.wins,
losses: tier.losses,
veteran: tier.veteran,
inactive: tier.inactive,
freshBlood: tier.freshBlood,
hotStreak: tier.hotStreak,
miniSeries: tier.miniSeries,
fetchedAt: tier.fetchedAt,
};
}
private async generateUniqueShortCode(
MatchModel: mongoose.Model<Match>,
communityId: mongoose.Types.ObjectId,
): Promise<string> {
for (
let attempt = 0;
attempt < MATCH_SHORT_CODE_GENERATION_ATTEMPTS;
attempt += 1
) {
const shortCode = this.generateShortCode();
const exists = await MatchModel.exists({ communityId, shortCode });
if (!exists) return shortCode;
}
throw new InternalServerErrorException(
'Failed to generate unique match short code.',
);
}
private generateShortCode(): string {
let code = '';
for (let index = 0; index < MATCH_SHORT_CODE_LENGTH; index += 1) {
const alphabetIndex = Math.floor(
Math.random() * MATCH_SHORT_CODE_ALPHABET.length,
);
code += MATCH_SHORT_CODE_ALPHABET[alphabetIndex];
}
return code;
}
private buildSeriesResults(
games: NonNullable<Match['result']>['games'],
): MatchSeriesResult[] {
const bySeries = new Map<string, MatchSeriesResult>();
for (const game of games) {
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,
} satisfies MatchSeriesResult);
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()];
}
}