This commit is contained in:
dahyeon committed 2026-04-24 13:40:39 -07:00
1 parent a197185ad0
commit 30dfb7ce58
27 files changed
+1584 -45

No files matched your search

+8
View File
@@ -2,7 +2,11 @@ import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuctionModule } from './modules/auction/auction.module';
import { AuthModule } from './modules/auth/auth.module';
import { CommunityModule } from './modules/community/community.module';
import { GlobalModule } from './modules/global/global.module';
import { MatchModule } from './modules/match/match.module';
import { RiotModule } from './modules/riot/riot.module';
@Module({
@@ -12,7 +16,11 @@ import { RiotModule } from './modules/riot/riot.module';
envFilePath: ['../project.env', 'project.env'],
}),
GlobalModule,
AuthModule,
RiotModule,
CommunityModule,
MatchModule,
AuctionModule,
],
controllers: [AppController],
providers: [AppService],
+9
View File
@@ -1,3 +1,4 @@
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
@@ -5,6 +6,14 @@ async function bootstrap() {
const app = await NestFactory.create(AppModule, {
rawBody: true,
});
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: { enableImplicitConversion: false },
}),
);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
@@ -0,0 +1,134 @@
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
Post,
UseGuards,
} from '@nestjs/common';
import mongoose from 'mongoose';
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 { UserDocument } from '../global/database/schema';
import { AuctionService } from './auction.service';
import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
@Controller('communities/:communityId/matches/:matchId/auction')
export class AuctionController {
constructor(private readonly auctionService: AuctionService) {}
@Post()
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async startAuction(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: StartAuctionDto,
) {
this.assertSameCommunity(currentUser, communityId);
return this.auctionService.start({
matchId,
communityId,
captains: body.captains.map((c) => ({
side: c.side,
userId: new mongoose.Types.ObjectId(c.userId),
})),
initialPoints: body.initialPoints ?? 1000,
maxTimerSeconds: body.maxTimerSeconds ?? 30,
});
}
@Get()
public async getAuction(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.auctionService.getByMatchId(matchId);
}
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
@Post('open-bidding')
@HttpCode(HttpStatus.OK)
public async openBidding(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.auctionService.openBidding(matchId);
}
@Post('bids')
@HttpCode(HttpStatus.OK)
public async placeBid(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: PlaceBidDto,
) {
return this.auctionService.placeBid({
matchId,
side: body.side,
amount: body.amount,
bidderUserId: this.resolveBidder(currentUser, body.bidderUserId),
});
}
@Post('sold')
@HttpCode(HttpStatus.OK)
public async markSold(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: SoldDto,
) {
return this.auctionService.markSold({
matchId,
assignedPosition: body.assignedPosition,
});
}
@Post('next')
@HttpCode(HttpStatus.OK)
public async next(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.auctionService.next(matchId);
}
@Delete()
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
@HttpCode(HttpStatus.NO_CONTENT)
public async resetAuction(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
this.assertSameCommunity(currentUser, communityId);
await this.auctionService.reset({ matchId, communityId });
}
private resolveBidder(
currentUser: UserDocument | undefined,
bodyBidder?: string,
): mongoose.Types.ObjectId | undefined {
if (currentUser) return currentUser._id;
if (!bodyBidder) return undefined;
if (!mongoose.isValidObjectId(bodyBidder)) {
throw new BadRequestException('Invalid bidderUserId.');
}
return new mongoose.Types.ObjectId(bodyBidder);
}
private assertSameCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!user.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { AuctionController } from './auction.controller';
import { AuctionService } from './auction.service';
@Module({
controllers: [AuctionController],
providers: [AuctionService],
exports: [AuctionService],
})
export class AuctionModule {}
@@ -0,0 +1,265 @@
import {
BadRequestException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
AuctionDocument,
AuctionPlayerSnapshot,
Position,
TeamSide,
} from '../global/database/schema';
interface StartAuctionParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
captains: { side: TeamSide; userId: mongoose.Types.ObjectId }[];
initialPoints: number;
maxTimerSeconds: number;
}
interface PlaceBidParams {
matchId: mongoose.Types.ObjectId;
side: TeamSide;
amount: number;
bidderUserId?: mongoose.Types.ObjectId;
}
interface MarkSoldParams {
matchId: mongoose.Types.ObjectId;
assignedPosition?: Position;
}
@Injectable()
export class AuctionService {
constructor(private readonly connectionService: ConnectionService) {}
public async start(params: StartAuctionParams): Promise<AuctionDocument> {
const MatchModel = await this.connectionService.getModel('match');
const UserModel = await this.connectionService.getModel('user');
const AuctionModel = await this.connectionService.getModel('auction');
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 existing = await AuctionModel.findOne({ matchId: params.matchId });
if (existing) {
throw new BadRequestException('Auction already exists for this match.');
}
const captainUserIds = params.captains.map((c) => c.userId);
if (captainUserIds[0].equals(captainUserIds[1])) {
throw new BadRequestException('Captains must be different users.');
}
const captainParticipants = match.participants.filter((p) =>
captainUserIds.some((cid) => cid.equals(p.userId)),
);
if (captainParticipants.length !== 2) {
throw new BadRequestException(
'Both captains must be participants of the match.',
);
}
const nonCaptainPuuids = new Set<string>();
const playerUsers = await UserModel.find({
_id: {
$in: match.participants
.filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId)))
.map((p) => p.userId),
},
});
const userById = new Map(playerUsers.map((u) => [u._id.toString(), u]));
const order: AuctionPlayerSnapshot[] = [];
for (const participant of match.participants) {
if (captainUserIds.some((cid) => cid.equals(participant.userId))) {
continue;
}
const user = userById.get(participant.userId.toString());
if (!user) continue;
const primary =
user.riotAccounts.find((a) => a.isPrimary) ?? user.riotAccounts[0];
if (!primary) {
throw new BadRequestException(
`Participant ${user._id.toString()} has no Riot account.`,
);
}
if (nonCaptainPuuids.has(primary.puuid)) continue;
nonCaptainPuuids.add(primary.puuid);
order.push({
userId: user._id,
puuid: primary.puuid,
gameName: primary.gameName,
tagLine: primary.tagLine,
profileIconId: primary.profileIconId,
preferredPositions: participant.preferredPositions,
tiers: primary.tiers,
masteries: primary.championMasteries,
recentStatsSummary: primary.recentStatsSummary,
});
}
const auction = await AuctionModel.create({
matchId: params.matchId,
phase: 'presenting',
teams: params.captains.map((c) => ({
side: c.side,
captainUserId: c.userId,
points: params.initialPoints,
members: [],
})),
order,
currentIndex: 0,
bids: [],
currentBid: 0,
maxTimerSeconds: params.maxTimerSeconds,
initialPoints: params.initialPoints,
startedAt: new Date(),
});
match.status = 'team-built';
await match.save();
return auction;
}
public async getByMatchId(
matchId: mongoose.Types.ObjectId,
): Promise<AuctionDocument> {
const AuctionModel = await this.connectionService.getModel('auction');
const auction = await AuctionModel.findOne({ matchId });
if (!auction) throw new NotFoundException('Auction not found.');
return auction;
}
public async openBidding(
matchId: mongoose.Types.ObjectId,
): Promise<AuctionDocument> {
const auction = await this.getByMatchId(matchId);
if (auction.phase !== 'presenting') {
throw new BadRequestException('Auction is not in presenting phase.');
}
auction.phase = 'bidding';
auction.currentBid = 0;
auction.currentBidder = undefined;
await auction.save();
return auction;
}
public async placeBid(params: PlaceBidParams): Promise<AuctionDocument> {
const auction = await this.getByMatchId(params.matchId);
if (auction.phase !== 'bidding') {
throw new BadRequestException('Auction is not in bidding phase.');
}
const team = auction.teams.find((t) => t.side === params.side);
if (!team) throw new BadRequestException('Unknown team side.');
if (params.amount <= auction.currentBid) {
throw new BadRequestException('Bid must exceed current bid.');
}
if (params.amount > team.points) {
throw new BadRequestException('Bid exceeds team points.');
}
auction.currentBid = params.amount;
auction.currentBidder = params.side;
auction.bids.push({
side: params.side,
amount: params.amount,
bidderUserId: params.bidderUserId ?? team.captainUserId,
timestamp: new Date(),
});
await auction.save();
return auction;
}
public async markSold(params: MarkSoldParams): Promise<AuctionDocument> {
const auction = await this.getByMatchId(params.matchId);
if (auction.phase !== 'bidding') {
throw new BadRequestException('Auction is not in bidding phase.');
}
if (!auction.currentBidder || auction.currentBid <= 0) {
throw new BadRequestException('No bid to mark sold.');
}
const team = auction.teams.find((t) => t.side === auction.currentBidder);
if (!team) throw new BadRequestException('Winning team not found.');
const current = auction.order[auction.currentIndex];
if (!current) throw new BadRequestException('No current player.');
const preferredPrimary = current.preferredPositions[0]?.position;
team.members.push({
userId: current.userId,
assignedPosition: params.assignedPosition ?? preferredPrimary ?? 'MID',
cost: auction.currentBid,
});
team.points -= auction.currentBid;
auction.phase = 'sold';
await auction.save();
return auction;
}
public async next(
matchId: mongoose.Types.ObjectId,
): Promise<AuctionDocument> {
const auction = await this.getByMatchId(matchId);
if (auction.phase !== 'sold' && auction.phase !== 'presenting') {
throw new BadRequestException('Cannot advance from current phase.');
}
const nextIndex = auction.currentIndex + 1;
if (nextIndex >= auction.order.length) {
auction.phase = 'complete';
auction.completedAt = new Date();
} else {
auction.currentIndex = nextIndex;
auction.phase = 'presenting';
auction.currentBid = 0;
auction.currentBidder = undefined;
}
await auction.save();
return auction;
}
public async reset(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
}): Promise<void> {
const AuctionModel = await this.connectionService.getModel('auction');
const MatchModel = await this.connectionService.getModel('match');
const session = await this.connectionService.createSession();
if (!session) {
throw new InternalServerErrorException('Failed to start DB session.');
}
try {
session.startTransaction();
const auction = await AuctionModel.findOne({
matchId: params.matchId,
}).session(session);
if (!auction) throw new NotFoundException('Auction not found.');
const match = await MatchModel.findById(params.matchId).session(session);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Community mismatch.');
}
await auction.deleteOne({ session });
if (match.status === 'team-built') {
match.status = 'recruiting';
await match.save({ session });
}
await session.commitTransaction();
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
await session.endSession();
}
}
}
@@ -0,0 +1,60 @@
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
ArrayMinSize,
IsArray,
IsEnum,
IsInt,
IsMongoId,
IsOptional,
Min,
ValidateNested,
} from 'class-validator';
import { TEAM_SIDES } from '../../global/database/schema';
import type { TeamSide } from '../../global/database/schema';
class CaptainAssignmentDto {
@IsEnum(TEAM_SIDES)
side!: TeamSide;
@IsMongoId()
userId!: string;
}
export class StartAuctionDto {
@IsArray()
@ArrayMinSize(2)
@ArrayMaxSize(2)
@ValidateNested({ each: true })
@Type(() => CaptainAssignmentDto)
captains!: CaptainAssignmentDto[];
@IsOptional()
@IsInt()
@Min(1)
initialPoints?: number;
@IsOptional()
@IsInt()
@Min(5)
maxTimerSeconds?: number;
}
export class PlaceBidDto {
@IsEnum(TEAM_SIDES)
side!: TeamSide;
@IsInt()
@Min(1)
amount!: number;
@IsOptional()
@IsMongoId()
bidderUserId?: string;
}
export class SoldDto {
@IsOptional()
@IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP'])
assignedPosition?: 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
}
@@ -0,0 +1,21 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import type { NextFunction, Request, Response } from 'express';
import { UserDocument } from '../global/database/schema';
import { AuthService } from './auth.service';
declare module 'express' {
interface Request {
user?: UserDocument;
}
}
@Injectable()
export class AuthMiddleware implements NestMiddleware {
constructor(private readonly authService: AuthService) {}
public async use(req: Request, _res: Response, next: NextFunction) {
const user = await this.authService.resolveUserFromRequest(req);
if (user) req.user = user;
next();
}
}
+15
View File
@@ -0,0 +1,15 @@
import { Global, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AuthMiddleware } from './auth.middleware';
import { AuthService } from './auth.service';
import { RolesGuard } from './roles.guard';
@Global()
@Module({
providers: [AuthService, RolesGuard],
exports: [AuthService, RolesGuard],
})
export class AuthModule implements NestModule {
public configure(consumer: MiddlewareConsumer) {
consumer.apply(AuthMiddleware).forRoutes('*');
}
}
+23
View File
@@ -0,0 +1,23 @@
import { Injectable } from '@nestjs/common';
import type { Request } from 'express';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { UserDocument } from '../global/database/schema';
@Injectable()
export class AuthService {
constructor(private readonly connectionService: ConnectionService) {}
// 로그인/세션 구현 전까지는 `X-Auth-User-Id` 헤더로 유저를 식별.
// OAuth 도입 시 이 메서드만 교체하면 됨.
public async resolveUserFromRequest(
req: Request,
): Promise<UserDocument | null> {
const header = req.headers['x-auth-user-id'];
const userId = Array.isArray(header) ? header[0] : header;
if (!userId || !mongoose.isValidObjectId(userId)) return null;
const UserModel = await this.connectionService.getModel('user');
return UserModel.findById(userId).exec();
}
}
@@ -0,0 +1,9 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { UserDocument } from '../global/database/schema';
export const CurrentUser = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): UserDocument | undefined => {
const req = ctx.switchToHttp().getRequest<{ user?: UserDocument }>();
return req.user;
},
);
+35
View File
@@ -0,0 +1,35 @@
import { CommunityRole } from '../global/database/schema';
export type Permission =
| 'community:edit'
| 'community:delete'
| 'community:transfer'
| 'user:role:manage'
| 'match:create'
| 'match:edit'
| 'match:delete'
| 'auction:manage';
type PermissionSet = readonly Permission[] | readonly ['*'];
export const ROLE_PERMISSIONS: Record<CommunityRole, PermissionSet> = {
owner: ['*'] as const,
admin: [
'community:edit',
'user:role:manage',
'match:create',
'match:edit',
'match:delete',
'auction:manage',
] as const,
member: [] as const,
};
export function roleHasPermission(
role: CommunityRole,
permission: Permission,
): boolean {
const perms = ROLE_PERMISSIONS[role];
if (perms.length === 1 && perms[0] === '*') return true;
return (perms as readonly Permission[]).includes(permission);
}
@@ -0,0 +1,7 @@
import { SetMetadata } from '@nestjs/common';
import { CommunityRole } from '../global/database/schema';
export const ROLES_KEY = 'lolympus:roles';
export const Roles = (...roles: CommunityRole[]) =>
SetMetadata(ROLES_KEY, roles);
+32
View File
@@ -0,0 +1,32 @@
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';
import { CommunityRole, UserDocument } from '../global/database/schema';
import { ROLES_KEY } from './roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
public canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<CommunityRole[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles || requiredRoles.length === 0) return true;
const req = context.switchToHttp().getRequest<Request>();
const user = req.user as UserDocument | undefined;
if (!user) throw new UnauthorizedException('Authentication required.');
if (!requiredRoles.includes(user.role)) {
throw new ForbiddenException('Insufficient role.');
}
return true;
}
}
@@ -0,0 +1,24 @@
import {
ArgumentMetadata,
BadRequestException,
Injectable,
PipeTransform,
} from '@nestjs/common';
import mongoose from 'mongoose';
@Injectable()
export class ParseObjectIdPipe
implements PipeTransform<string, mongoose.Types.ObjectId>
{
public transform(
value: string,
metadata: ArgumentMetadata,
): mongoose.Types.ObjectId {
if (!mongoose.isValidObjectId(value)) {
throw new BadRequestException(
`Invalid ObjectId for ${metadata.data ?? 'param'}.`,
);
}
return new mongoose.Types.ObjectId(value);
}
}
@@ -0,0 +1,80 @@
import {
Body,
Controller,
ForbiddenException,
Param,
Patch,
Post,
UseGuards,
} from '@nestjs/common';
import mongoose from 'mongoose';
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 { UserDocument } from '../global/database/schema';
import { CommunityService } from './community.service';
import { CreateCommunityDto } from './dto/create-community.dto';
import { TransferOwnershipDto } from './dto/transfer-ownership.dto';
@Controller('communities')
export class CommunityController {
constructor(private readonly communityService: CommunityService) {}
@Post()
public async createCommunity(@Body() body: CreateCommunityDto) {
return this.communityService.createCommunityWithOwner(body);
}
@Patch(':communityId/members/:userId/promote')
@Roles('owner')
@UseGuards(RolesGuard)
public async promoteToAdmin(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId,
) {
this.assertOwnerOfCommunity(currentUser, communityId);
return this.communityService.promoteToAdmin({ communityId, targetUserId });
}
@Patch(':communityId/members/:userId/demote')
@Roles('owner')
@UseGuards(RolesGuard)
public async demoteToMember(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId,
) {
this.assertOwnerOfCommunity(currentUser, communityId);
return this.communityService.demoteToMember({ communityId, targetUserId });
}
@Patch(':communityId/transfer-ownership')
@Roles('owner')
@UseGuards(RolesGuard)
public async transferOwnership(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Body() body: TransferOwnershipDto,
) {
this.assertOwnerOfCommunity(currentUser, communityId);
return this.communityService.transferOwnership({
communityId,
currentOwnerUserId: currentUser._id,
newOwnerUserId: new mongoose.Types.ObjectId(body.newOwnerUserId),
});
}
private assertOwnerOfCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!user.communityId.equals(communityId)) {
throw new ForbiddenException('You do not belong to this community.');
}
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { CommunityController } from './community.controller';
import { CommunityService } from './community.service';
@Module({
controllers: [CommunityController],
providers: [CommunityService],
exports: [CommunityService],
})
export class CommunityModule {}
@@ -0,0 +1,185 @@
import {
BadRequestException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
CommunityDocument,
UserDocument,
} from '../global/database/schema';
export interface CreateCommunityInput {
name: string;
description?: string;
owner: {
kakaoTalkId?: string;
kakaoTalkNickname?: string;
discordId?: string;
discordNickname?: string;
};
}
@Injectable()
export class CommunityService {
constructor(private readonly connectionService: ConnectionService) {}
public async createCommunityWithOwner(input: CreateCommunityInput): Promise<{
community: CommunityDocument;
owner: UserDocument;
}> {
const CommunityModel = await this.connectionService.getModel('community');
const UserModel = await this.connectionService.getModel('user');
const communityId = new mongoose.Types.ObjectId();
const ownerUserId = new mongoose.Types.ObjectId();
const session = await this.connectionService.createSession();
if (!session) {
throw new InternalServerErrorException('Failed to start DB session.');
}
try {
session.startTransaction();
const [community] = await CommunityModel.create(
[
{
_id: communityId,
name: input.name,
description: input.description ?? '',
ownerUserId,
},
],
{ session },
);
const [owner] = await UserModel.create(
[
{
_id: ownerUserId,
communityId,
role: 'owner',
kakaoTalkId: input.owner.kakaoTalkId,
kakaoTalkNickname: input.owner.kakaoTalkNickname,
discordId: input.owner.discordId,
discordNickname: input.owner.discordNickname,
},
],
{ session },
);
await session.commitTransaction();
return { community, owner };
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
await session.endSession();
}
}
public async promoteToAdmin(params: {
communityId: mongoose.Types.ObjectId;
targetUserId: mongoose.Types.ObjectId;
}): Promise<UserDocument> {
return this.changeNonOwnerRole({ ...params, nextRole: 'admin' });
}
public async demoteToMember(params: {
communityId: mongoose.Types.ObjectId;
targetUserId: mongoose.Types.ObjectId;
}): Promise<UserDocument> {
return this.changeNonOwnerRole({ ...params, nextRole: 'member' });
}
public async transferOwnership(params: {
communityId: mongoose.Types.ObjectId;
currentOwnerUserId: mongoose.Types.ObjectId;
newOwnerUserId: mongoose.Types.ObjectId;
}): Promise<{
community: CommunityDocument;
previousOwner: UserDocument;
newOwner: UserDocument;
}> {
if (params.currentOwnerUserId.equals(params.newOwnerUserId)) {
throw new BadRequestException('New owner is already the current owner.');
}
const CommunityModel = await this.connectionService.getModel('community');
const UserModel = await this.connectionService.getModel('user');
const session = await this.connectionService.createSession();
if (!session) {
throw new InternalServerErrorException('Failed to start DB session.');
}
try {
session.startTransaction();
const community = await CommunityModel.findById(
params.communityId,
).session(session);
if (!community) throw new NotFoundException('Community not found.');
if (!community.ownerUserId.equals(params.currentOwnerUserId)) {
throw new BadRequestException('Acting user is not the current owner.');
}
const [previousOwner, newOwner] = await Promise.all([
UserModel.findById(params.currentOwnerUserId).session(session),
UserModel.findById(params.newOwnerUserId).session(session),
]);
if (!previousOwner)
throw new NotFoundException('Previous owner user not found.');
if (!newOwner) throw new NotFoundException('New owner user not found.');
if (!newOwner.communityId.equals(params.communityId)) {
throw new BadRequestException(
'New owner does not belong to this community.',
);
}
community.ownerUserId = newOwner._id;
previousOwner.role = 'admin';
newOwner.role = 'owner';
await Promise.all([
community.save({ session }),
previousOwner.save({ session }),
newOwner.save({ session }),
]);
await session.commitTransaction();
return { community, previousOwner, newOwner };
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
await session.endSession();
}
}
private async changeNonOwnerRole(params: {
communityId: mongoose.Types.ObjectId;
targetUserId: mongoose.Types.ObjectId;
nextRole: 'admin' | 'member';
}): Promise<UserDocument> {
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.targetUserId);
if (!user) throw new NotFoundException('Target user not found.');
if (!user.communityId.equals(params.communityId)) {
throw new BadRequestException(
'Target user does not belong to this community.',
);
}
if (user.role === 'owner') {
throw new BadRequestException(
'Owner role must be changed via transferOwnership.',
);
}
user.role = params.nextRole;
await user.save();
return user;
}
}
@@ -0,0 +1,46 @@
import { Type } from 'class-transformer';
import {
IsOptional,
IsString,
MaxLength,
MinLength,
ValidateNested,
} from 'class-validator';
class CreateCommunityOwnerDto {
@IsOptional()
@IsString()
@MaxLength(64)
kakaoTalkId?: string;
@IsOptional()
@IsString()
@MaxLength(64)
kakaoTalkNickname?: string;
@IsOptional()
@IsString()
@MaxLength(64)
discordId?: string;
@IsOptional()
@IsString()
@MaxLength(64)
discordNickname?: string;
}
export class CreateCommunityDto {
@IsString()
@MinLength(1)
@MaxLength(64)
name!: string;
@IsOptional()
@IsString()
@MaxLength(1024)
description?: string;
@ValidateNested()
@Type(() => CreateCommunityOwnerDto)
owner!: CreateCommunityOwnerDto;
}
@@ -0,0 +1,6 @@
import { IsMongoId } from 'class-validator';
export class TransferOwnershipDto {
@IsMongoId()
newOwnerUserId!: string;
}
@@ -1,10 +1,7 @@
import { Injectable, Scope, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose';
import { SecretService } from '../secret/secret.service';
import {
tournamentModelDefinitions,
TournamentModelTypes,
} from './schema';
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
@Injectable({ scope: Scope.DEFAULT })
export class ConnectionService implements OnModuleInit {
@@ -23,7 +20,7 @@ export class ConnectionService implements OnModuleInit {
);
const defaultConnection = await mongoose
.createConnection(connectionString, {
dbName: 'tournament',
dbName: 'lolympus',
minPoolSize: 10,
maxPoolSize: 20,
})
+85 -15
View File
@@ -19,6 +19,14 @@ export const MATCH_STATUSES: MatchStatus[] = [
export type TeamSide = 'blue' | 'red';
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
export type CommunityRole = 'owner' | 'admin' | 'member';
export const COMMUNITY_ROLES: CommunityRole[] = ['owner', 'admin', 'member'];
export interface PositionPreference {
position: Position;
priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위
}
export type AuctionPhase =
| 'waiting'
| 'presenting'
@@ -119,15 +127,24 @@ export interface RiotAccount extends MongooseTimestamps {
// ===== User =====
export interface User extends MongooseTimestamps {
communityId: mongoose.Types.ObjectId;
role: CommunityRole;
kakaoTalkId?: string;
kakaoTalkNickname?: string;
discordId?: string;
discordNickname?: string;
riotAccounts: RiotAccount[];
preferredPositions: Position[];
preferredPositions: PositionPreference[];
isActivated: boolean;
}
export interface Community extends MongooseTimestamps {
name: string;
description: string;
ownerUserId: mongoose.Types.ObjectId;
}
export type CommunityDocument = HydratedDocument<Community>;
export type UserDocument = HydratedDocument<User>;
// ===== RiotMatch (Riot 원본 매치 아카이브) =====
@@ -152,7 +169,7 @@ export interface MatchParticipant {
gameName?: string;
tagLine?: string;
profileIconId?: number;
preferredPositions: Position[];
preferredPositions: PositionPreference[];
joinedAt: Date;
}
@@ -183,9 +200,10 @@ export interface MatchScheduleItem {
}
export interface Match extends MongooseTimestamps {
communityId: mongoose.Types.ObjectId;
title: string;
description: string;
map: string;
mapId: number; // Riot Match-V5 mapId (11=소환사의 협곡, 12=ARAM 등)
status: MatchStatus;
scheduledAt: Date;
maxParticipants: number;
@@ -208,7 +226,7 @@ export interface AuctionPlayerSnapshot {
gameName: string;
tagLine: string;
profileIconId: number;
preferredPositions: Position[];
preferredPositions: PositionPreference[];
tiers: TierInfo[];
masteries: ChampionMasteryEntry[];
recentStatsSummary?: RiotRecentStatsSummary;
@@ -230,7 +248,7 @@ export interface AuctionTeam {
export interface AuctionBid {
side: TeamSide;
amount: number;
bidderUserId?: mongoose.Types.ObjectId;
bidderUserId: mongoose.Types.ObjectId;
timestamp: Date;
}
@@ -252,6 +270,14 @@ export interface Auction extends MongooseTimestamps {
export type AuctionDocument = HydratedDocument<Auction>;
// ===== Sub-schemas =====
const PositionPreferenceSubSchema = new Schema<PositionPreference>(
{
position: { type: String, enum: POSITIONS, required: true },
priority: { type: Number, required: true, min: 1 },
},
{ _id: false },
);
const TierInfoSubSchema = new Schema<TierInfo>(
{
queueType: { type: String, required: true },
@@ -346,8 +372,34 @@ const RiotAccountSubSchema = new Schema<RiotAccount>(
},
);
export const CommunitySchema = new Schema<Community>(
{
name: { type: String, required: true },
description: { type: String, required: true, default: '' },
ownerUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
},
{
timestamps: true,
collection: 'community',
},
);
CommunitySchema.index({ name: 1 }, { unique: true });
CommunitySchema.index({ ownerUserId: 1 });
export const UserSchema = new Schema<User>(
{
communityId: {
type: Schema.Types.ObjectId,
ref: 'community',
required: true,
},
role: {
type: String,
enum: COMMUNITY_ROLES,
required: true,
default: 'member',
},
kakaoTalkId: { type: String },
kakaoTalkNickname: { type: String },
discordId: { type: String },
@@ -376,7 +428,7 @@ export const UserSchema = new Schema<User>(
],
},
preferredPositions: {
type: [{ type: String, enum: POSITIONS }],
type: [PositionPreferenceSubSchema],
required: true,
default: [],
},
@@ -388,9 +440,20 @@ export const UserSchema = new Schema<User>(
},
);
UserSchema.index({ kakaoTalkId: 1 }, { unique: true, sparse: true });
UserSchema.index({ discordId: 1 }, { unique: true, sparse: true });
UserSchema.index({ 'riotAccounts.puuid': 1 }, { unique: true, sparse: true });
UserSchema.index({ communityId: 1 });
UserSchema.index({ communityId: 1, role: 1 });
UserSchema.index(
{ communityId: 1, kakaoTalkId: 1 },
{ unique: true, sparse: true },
);
UserSchema.index(
{ communityId: 1, discordId: 1 },
{ unique: true, sparse: true },
);
UserSchema.index(
{ communityId: 1, 'riotAccounts.puuid': 1 },
{ unique: true, sparse: true },
);
export const RiotMatchSchema = new Schema<RiotMatch>(
{
@@ -419,7 +482,7 @@ const MatchParticipantSubSchema = new Schema<MatchParticipant>(
tagLine: { type: String },
profileIconId: { type: Number },
preferredPositions: {
type: [{ type: String, enum: POSITIONS }],
type: [PositionPreferenceSubSchema],
required: true,
default: [],
},
@@ -468,9 +531,14 @@ const MatchScheduleItemSubSchema = new Schema<MatchScheduleItem>(
export const MatchSchema = new Schema<Match>(
{
communityId: {
type: Schema.Types.ObjectId,
ref: 'community',
required: true,
},
title: { type: String, required: true },
description: { type: String, required: true, default: '' },
map: { type: String, required: true, default: '소환사의 협곡' },
mapId: { type: Number, required: true, default: 11 },
status: {
type: String,
enum: MATCH_STATUSES,
@@ -508,8 +576,8 @@ export const MatchSchema = new Schema<Match>(
},
);
MatchSchema.index({ scheduledAt: -1 });
MatchSchema.index({ status: 1, scheduledAt: -1 });
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
MatchSchema.index({ title: 'text', description: 'text' });
const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
@@ -520,7 +588,7 @@ const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
tagLine: { type: String, required: true },
profileIconId: { type: Number, required: true, default: 0 },
preferredPositions: {
type: [{ type: String, enum: POSITIONS }],
type: [PositionPreferenceSubSchema],
required: true,
default: [],
},
@@ -562,7 +630,7 @@ const AuctionBidSubSchema = new Schema<AuctionBid>(
{
side: { type: String, enum: TEAM_SIDES, required: true },
amount: { type: Number, required: true },
bidderUserId: { type: Schema.Types.ObjectId, ref: 'user' },
bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
timestamp: { type: Date, required: true, default: Date.now },
},
{ _id: false },
@@ -604,6 +672,7 @@ export const AuctionSchema = new Schema<Auction>(
);
export const tournamentModelDefinitions: ModelDefinition[] = [
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
{ name: 'user', schema: UserSchema, schemaName: 'user' },
{ name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' },
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
@@ -611,6 +680,7 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
];
export interface TournamentModelTypes {
community: Community;
user: User;
riotMatch: RiotMatch;
match: Match;
@@ -0,0 +1,135 @@
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
ArrayMinSize,
IsArray,
IsDate,
IsEnum,
IsInt,
IsOptional,
IsString,
MaxLength,
Min,
MinLength,
ValidateNested,
} from 'class-validator';
import { POSITIONS } from '../../global/database/schema';
import type { Position } from '../../global/database/schema';
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(2)
maxParticipants?: number;
@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(2)
maxParticipants?: number;
@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,163 @@
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import mongoose from 'mongoose';
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,
prizes: body.prizes ?? [],
notices: body.notices ?? [],
schedule: body.schedule ?? [],
},
});
}
// 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환.
@Get()
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')
public async getMatch(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.matchService.getById(matchId);
}
@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')
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,10 @@
import { Module } from '@nestjs/common';
import { MatchController } from './match.controller';
import { MatchService } from './match.service';
@Module({
controllers: [MatchController],
providers: [MatchService],
exports: [MatchService],
})
export class MatchModule {}
+138
View File
@@ -0,0 +1,138 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
Match,
MatchDocument,
MatchStatus,
PositionPreference,
} from '../global/database/schema';
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[];
}
@Injectable()
export class MatchService {
constructor(private readonly connectionService: ConnectionService) {}
public async create(params: CreateMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
return MatchModel.create({
...params.data,
communityId: params.communityId,
hostUserId: params.hostUserId,
});
}
public async list(query: ListMatchesQuery): Promise<MatchDocument[]> {
const MatchModel = await this.connectionService.getModel('match');
const filter: mongoose.FilterQuery<Match> = {
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 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 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.');
}
match.set(params.patch);
await match.save();
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 match.deleteOne();
}
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 primaryRiot = user.riotAccounts.find((a) => a.isPrimary);
match.participants.push({
userId: user._id,
puuid: primaryRiot?.puuid,
gameName: primaryRiot?.gameName,
tagLine: primaryRiot?.tagLine,
profileIconId: primaryRiot?.profileIconId,
preferredPositions: params.preferredPositions,
joinedAt: new Date(),
});
await match.save();
return match;
}
}