.
This commit is contained in:
1 parent
30dfb7ce58
commit
5af2c80cd1
33 files changed
+3806
-1440
No files matched your search
@@ -8,6 +8,7 @@
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"seed:dev": "ts-node src/seed.ts",
|
||||
"start:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./start.ps1\"\"",
|
||||
"start:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); \"./start.ps1\"\"",
|
||||
"start:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); \"./start.ps1\"\"",
|
||||
@@ -27,13 +28,16 @@
|
||||
"@nestjs/config": "^4.0.4",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/platform-socket.io": "^11.1.19",
|
||||
"@nestjs/swagger": "^11.2.7",
|
||||
"@nestjs/websockets": "^11.1.19",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"mongoose": "^9.4.1",
|
||||
"nats": "^2.29.3",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"socket.io": "^4.8.3",
|
||||
"temporal-polyfill": "^0.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -8,6 +8,7 @@ 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';
|
||||
import { UserModule } from './modules/user/user.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -21,6 +22,7 @@ import { RiotModule } from './modules/riot/riot.module';
|
||||
CommunityModule,
|
||||
MatchModule,
|
||||
AuctionModule,
|
||||
UserModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
|
||||
@@ -6,6 +6,17 @@ async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule, {
|
||||
rawBody: true,
|
||||
});
|
||||
|
||||
const isDev = process.env.NODE_ENV === 'dev';
|
||||
const webOrigins = process.env.WEB_ORIGIN?.split(',').map((origin) =>
|
||||
origin.trim(),
|
||||
) ?? ['http://localhost:5173', 'http://126.dahyeon.us:5173'];
|
||||
|
||||
app.enableCors({
|
||||
origin: isDev ? true : webOrigins,
|
||||
credentials: true,
|
||||
allowedHeaders: ['Content-Type', 'X-Auth-User-Id'],
|
||||
});
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import {
|
||||
ConnectedSocket,
|
||||
MessageBody,
|
||||
OnGatewayConnection,
|
||||
OnGatewayDisconnect,
|
||||
SubscribeMessage,
|
||||
WebSocketGateway,
|
||||
WebSocketServer,
|
||||
} from '@nestjs/websockets';
|
||||
import mongoose from 'mongoose';
|
||||
import { Namespace, Socket } from 'socket.io';
|
||||
import type { AuctionDocument, Position, TeamSide } from '../global/database/schema';
|
||||
import { AuctionService } from './auction.service';
|
||||
|
||||
interface JoinAuctionPayload {
|
||||
matchId: string;
|
||||
}
|
||||
|
||||
interface BidPayload {
|
||||
side: TeamSide;
|
||||
amount: number;
|
||||
bidderUserId?: string;
|
||||
}
|
||||
|
||||
interface SoldPayload {
|
||||
assignedPosition?: Position;
|
||||
}
|
||||
|
||||
@WebSocketGateway({
|
||||
namespace: '/auction',
|
||||
cors: {
|
||||
origin: true,
|
||||
credentials: true,
|
||||
allowedHeaders: ['Content-Type', 'X-Auth-User-Id'],
|
||||
},
|
||||
})
|
||||
export class AuctionGateway
|
||||
implements OnGatewayConnection, OnGatewayDisconnect
|
||||
{
|
||||
@WebSocketServer()
|
||||
private server!: Namespace;
|
||||
|
||||
private readonly logger = new Logger(AuctionGateway.name);
|
||||
private readonly roomTimers = new Map<string, NodeJS.Timeout>();
|
||||
|
||||
constructor(private readonly auctionService: AuctionService) {}
|
||||
|
||||
public handleConnection(socket: Socket) {
|
||||
this.logger.debug(`Auction client connected: ${socket.id}`);
|
||||
}
|
||||
|
||||
public handleDisconnect(socket: Socket) {
|
||||
const matchId = this.getSocketMatchId(socket);
|
||||
if (!matchId) return;
|
||||
this.maybeClearRoomTimer(matchId);
|
||||
}
|
||||
|
||||
@SubscribeMessage('join')
|
||||
public async handleJoin(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@MessageBody() payload: JoinAuctionPayload,
|
||||
) {
|
||||
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
|
||||
this.emitError(socket, 'Invalid matchId.');
|
||||
return;
|
||||
}
|
||||
|
||||
await socket.join(payload.matchId);
|
||||
socket.data.matchId = payload.matchId;
|
||||
|
||||
try {
|
||||
const auction = await this.auctionService.getByMatchId(
|
||||
new mongoose.Types.ObjectId(payload.matchId),
|
||||
);
|
||||
this.broadcastState(payload.matchId, auction);
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeMessage('bid')
|
||||
public async handleBid(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@MessageBody() payload: BidPayload,
|
||||
) {
|
||||
const matchId = this.requireJoinedMatchId(socket);
|
||||
if (!matchId) return;
|
||||
|
||||
const bidderUserId = this.resolveBidderUserId(socket, payload?.bidderUserId);
|
||||
if (payload?.bidderUserId && !bidderUserId) {
|
||||
this.emitError(socket, 'Invalid bidderUserId.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const auction = await this.auctionService.placeBid({
|
||||
matchId: new mongoose.Types.ObjectId(matchId),
|
||||
side: payload.side,
|
||||
amount: payload.amount,
|
||||
bidderUserId,
|
||||
});
|
||||
this.broadcastState(matchId, auction);
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeMessage('open-bidding')
|
||||
public async handleOpenBidding(@ConnectedSocket() socket: Socket) {
|
||||
const matchId = this.requireJoinedMatchId(socket);
|
||||
if (!matchId) return;
|
||||
|
||||
try {
|
||||
const auction = await this.auctionService.openBidding(
|
||||
new mongoose.Types.ObjectId(matchId),
|
||||
);
|
||||
this.broadcastState(matchId, auction);
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeMessage('sold')
|
||||
public async handleSold(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@MessageBody() payload: SoldPayload,
|
||||
) {
|
||||
const matchId = this.requireJoinedMatchId(socket);
|
||||
if (!matchId) return;
|
||||
|
||||
try {
|
||||
const auction = await this.auctionService.markSold({
|
||||
matchId: new mongoose.Types.ObjectId(matchId),
|
||||
assignedPosition: payload?.assignedPosition,
|
||||
});
|
||||
this.broadcastState(matchId, auction);
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeMessage('next')
|
||||
public async handleNext(@ConnectedSocket() socket: Socket) {
|
||||
const matchId = this.requireJoinedMatchId(socket);
|
||||
if (!matchId) return;
|
||||
|
||||
try {
|
||||
const auction = await this.auctionService.next(
|
||||
new mongoose.Types.ObjectId(matchId),
|
||||
);
|
||||
this.broadcastState(matchId, auction);
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
}
|
||||
}
|
||||
|
||||
private requireJoinedMatchId(socket: Socket): string | null {
|
||||
const matchId = this.getSocketMatchId(socket);
|
||||
if (!matchId) {
|
||||
this.emitError(socket, 'Join a match room before sending events.');
|
||||
return null;
|
||||
}
|
||||
return matchId;
|
||||
}
|
||||
|
||||
private getSocketMatchId(socket: Socket): string | undefined {
|
||||
return typeof socket.data.matchId === 'string' ? socket.data.matchId : undefined;
|
||||
}
|
||||
|
||||
private resolveBidderUserId(
|
||||
socket: Socket,
|
||||
payloadBidderUserId?: string,
|
||||
): mongoose.Types.ObjectId | undefined {
|
||||
const candidate =
|
||||
payloadBidderUserId ?? this.readHandshakeUserId(socket);
|
||||
if (!candidate || !mongoose.isValidObjectId(candidate)) {
|
||||
return undefined;
|
||||
}
|
||||
return new mongoose.Types.ObjectId(candidate);
|
||||
}
|
||||
|
||||
private readHandshakeUserId(socket: Socket): string | undefined {
|
||||
const authUserId = socket.handshake.auth['x-auth-user-id'];
|
||||
if (typeof authUserId === 'string') return authUserId;
|
||||
|
||||
const header = socket.handshake.headers['x-auth-user-id'];
|
||||
return Array.isArray(header) ? header[0] : header;
|
||||
}
|
||||
|
||||
private broadcastState(matchId: string, auction: AuctionDocument) {
|
||||
this.server.to(matchId).emit('state', this.serializeAuction(auction));
|
||||
this.syncRoomTimer(matchId, auction);
|
||||
}
|
||||
|
||||
private syncRoomTimer(matchId: string, auction: AuctionDocument) {
|
||||
this.clearRoomTimer(matchId);
|
||||
if (!auction.currentDeadline) return;
|
||||
|
||||
const deadline = auction.currentDeadline;
|
||||
const deadlineIso = deadline.toISOString();
|
||||
this.server.to(matchId).emit('tick', {
|
||||
deadline: deadlineIso,
|
||||
serverTime: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const timer = setInterval(() => {
|
||||
this.server.to(matchId).emit('tick', {
|
||||
deadline: deadlineIso,
|
||||
serverTime: new Date().toISOString(),
|
||||
});
|
||||
|
||||
if (Date.now() >= deadline.getTime()) {
|
||||
this.clearRoomTimer(matchId);
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
this.roomTimers.set(matchId, timer);
|
||||
}
|
||||
|
||||
private maybeClearRoomTimer(matchId: string) {
|
||||
const room = this.server.adapter.rooms.get(matchId);
|
||||
if (room && room.size > 0) return;
|
||||
this.clearRoomTimer(matchId);
|
||||
}
|
||||
|
||||
private clearRoomTimer(matchId: string) {
|
||||
const timer = this.roomTimers.get(matchId);
|
||||
if (!timer) return;
|
||||
clearInterval(timer);
|
||||
this.roomTimers.delete(matchId);
|
||||
}
|
||||
|
||||
private emitKnownError(socket: Socket, error: unknown) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : 'Unexpected auction gateway error.';
|
||||
this.emitError(socket, message);
|
||||
}
|
||||
|
||||
private emitError(socket: Socket, message: string) {
|
||||
socket.emit('error', { message });
|
||||
}
|
||||
|
||||
private serializeAuction(auction: AuctionDocument) {
|
||||
return JSON.parse(JSON.stringify(auction));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuctionGateway } from './auction.gateway';
|
||||
import { AuctionController } from './auction.controller';
|
||||
import { AuctionService } from './auction.service';
|
||||
|
||||
@Module({
|
||||
controllers: [AuctionController],
|
||||
providers: [AuctionService],
|
||||
providers: [AuctionService, AuctionGateway],
|
||||
exports: [AuctionService],
|
||||
})
|
||||
export class AuctionModule {}
|
||||
@@ -148,6 +148,7 @@ export class AuctionService {
|
||||
auction.phase = 'bidding';
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidder = undefined;
|
||||
auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds);
|
||||
await auction.save();
|
||||
return auction;
|
||||
}
|
||||
@@ -165,9 +166,18 @@ export class AuctionService {
|
||||
if (params.amount > team.points) {
|
||||
throw new BadRequestException('Bid exceeds team points.');
|
||||
}
|
||||
if (
|
||||
params.bidderUserId &&
|
||||
!team.captainUserId.equals(params.bidderUserId)
|
||||
) {
|
||||
throw new BadRequestException('Bidder is not the captain of this team.');
|
||||
}
|
||||
|
||||
auction.currentBid = params.amount;
|
||||
auction.currentBidder = params.side;
|
||||
auction.currentDeadline = this.createDeadline(
|
||||
this.resolveBidExtensionSeconds(auction),
|
||||
);
|
||||
auction.bids.push({
|
||||
side: params.side,
|
||||
amount: params.amount,
|
||||
@@ -200,6 +210,7 @@ export class AuctionService {
|
||||
});
|
||||
team.points -= auction.currentBid;
|
||||
auction.phase = 'sold';
|
||||
auction.currentDeadline = undefined;
|
||||
await auction.save();
|
||||
return auction;
|
||||
}
|
||||
@@ -221,6 +232,7 @@ export class AuctionService {
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidder = undefined;
|
||||
}
|
||||
auction.currentDeadline = undefined;
|
||||
await auction.save();
|
||||
return auction;
|
||||
}
|
||||
@@ -262,4 +274,19 @@ export class AuctionService {
|
||||
await session.endSession();
|
||||
}
|
||||
}
|
||||
|
||||
private createDeadline(secondsFromNow: number): Date {
|
||||
return new Date(Date.now() + secondsFromNow * 1000);
|
||||
}
|
||||
|
||||
private resolveBidExtensionSeconds(auction: AuctionDocument): number {
|
||||
if (!auction.currentDeadline) {
|
||||
return auction.maxTimerSeconds;
|
||||
}
|
||||
|
||||
const remainingSeconds = Math.ceil(
|
||||
(auction.currentDeadline.getTime() - Date.now()) / 1000,
|
||||
);
|
||||
return Math.max(5, remainingSeconds);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
@@ -26,6 +27,14 @@ export class CommunityController {
|
||||
return this.communityService.createCommunityWithOwner(body);
|
||||
}
|
||||
|
||||
@Get(':communityId')
|
||||
public async getCommunity(
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
return this.communityService.getById(communityId);
|
||||
}
|
||||
|
||||
@Patch(':communityId/members/:userId/promote')
|
||||
@Roles('owner')
|
||||
@UseGuards(RolesGuard)
|
||||
|
||||
@@ -26,6 +26,15 @@ export interface CreateCommunityInput {
|
||||
export class CommunityService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async getById(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<CommunityDocument> {
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const community = await CommunityModel.findById(communityId).exec();
|
||||
if (!community) throw new NotFoundException('Community not found.');
|
||||
return community;
|
||||
}
|
||||
|
||||
public async createCommunityWithOwner(input: CreateCommunityInput): Promise<{
|
||||
community: CommunityDocument;
|
||||
owner: UserDocument;
|
||||
|
||||
@@ -169,6 +169,7 @@ export interface MatchParticipant {
|
||||
gameName?: string;
|
||||
tagLine?: string;
|
||||
profileIconId?: number;
|
||||
tier?: TierInfo;
|
||||
preferredPositions: PositionPreference[];
|
||||
joinedAt: Date;
|
||||
}
|
||||
@@ -262,6 +263,7 @@ export interface Auction extends MongooseTimestamps {
|
||||
currentBid: number;
|
||||
currentBidder?: TeamSide;
|
||||
maxTimerSeconds: number;
|
||||
currentDeadline?: Date;
|
||||
initialPoints: number;
|
||||
startedAt?: Date;
|
||||
completedAt?: Date;
|
||||
@@ -481,6 +483,7 @@ const MatchParticipantSubSchema = new Schema<MatchParticipant>(
|
||||
gameName: { type: String },
|
||||
tagLine: { type: String },
|
||||
profileIconId: { type: Number },
|
||||
tier: { type: TierInfoSubSchema },
|
||||
preferredPositions: {
|
||||
type: [PositionPreferenceSubSchema],
|
||||
required: true,
|
||||
@@ -661,6 +664,7 @@ export const AuctionSchema = new Schema<Auction>(
|
||||
currentBid: { type: Number, required: true, default: 0 },
|
||||
currentBidder: { type: String, enum: TEAM_SIDES, required: false },
|
||||
maxTimerSeconds: { type: Number, required: true, default: 30 },
|
||||
currentDeadline: { type: Date, required: false },
|
||||
initialPoints: { type: Number, required: true, default: 1000 },
|
||||
startedAt: { type: Date, required: false },
|
||||
completedAt: { type: Date, required: false },
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
MatchDocument,
|
||||
MatchStatus,
|
||||
PositionPreference,
|
||||
TierInfo,
|
||||
} from '../global/database/schema';
|
||||
|
||||
interface CreateMatchParams {
|
||||
@@ -51,7 +52,10 @@ export class MatchService {
|
||||
|
||||
public async list(query: ListMatchesQuery): Promise<MatchDocument[]> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const filter: mongoose.FilterQuery<Match> = {
|
||||
const filter: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
status?: MatchStatus;
|
||||
} = {
|
||||
communityId: query.communityId,
|
||||
};
|
||||
if (query.status) filter.status = query.status;
|
||||
@@ -123,16 +127,34 @@ export class MatchService {
|
||||
}
|
||||
|
||||
const primaryRiot = user.riotAccounts.find((a) => a.isPrimary);
|
||||
const primaryTier = this.selectParticipantTier(primaryRiot?.tiers ?? []);
|
||||
match.participants.push({
|
||||
userId: user._id,
|
||||
puuid: primaryRiot?.puuid,
|
||||
gameName: primaryRiot?.gameName,
|
||||
tagLine: primaryRiot?.tagLine,
|
||||
profileIconId: primaryRiot?.profileIconId,
|
||||
tier: primaryTier,
|
||||
preferredPositions: params.preferredPositions,
|
||||
joinedAt: new Date(),
|
||||
});
|
||||
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 {
|
||||
queueType: tier.queueType,
|
||||
tier: tier.tier,
|
||||
rank: tier.rank,
|
||||
leaguePoints: tier.leaguePoints,
|
||||
wins: tier.wins,
|
||||
losses: tier.losses,
|
||||
fetchedAt: tier.fetchedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ describe('RiotWebhookController', () => {
|
||||
eventType: 'MATCH_FINISHED',
|
||||
},
|
||||
rawBody: Buffer.from('{"eventType":"MATCH_FINISHED"}', 'utf8'),
|
||||
} as RiotWebhookRequest;
|
||||
} as unknown as RiotWebhookRequest;
|
||||
|
||||
const response = controller.captureTournamentWebhook(request);
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
|
||||
@Controller('me')
|
||||
export class UserController {
|
||||
@Get()
|
||||
public me(@CurrentUser() user: UserDocument | undefined) {
|
||||
return { user: user ?? null };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UserController } from './user.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [UserController],
|
||||
})
|
||||
export class UserModule {}
|
||||
@@ -0,0 +1,913 @@
|
||||
import 'reflect-metadata';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import mongoose from 'mongoose';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import { ConnectionService } from './modules/global/database/connection.service';
|
||||
import type {
|
||||
ChampionMasteryEntry,
|
||||
MatchParticipant,
|
||||
MatchTeam,
|
||||
Position,
|
||||
PositionPreference,
|
||||
RiotRecentStatsSummary,
|
||||
TierInfo,
|
||||
} from './modules/global/database/schema';
|
||||
import { SecretModule } from './modules/global/secret/secret.module';
|
||||
|
||||
process.env.NODE_ENV ??= 'dev';
|
||||
|
||||
async function loadMachineEnvFile() {
|
||||
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
|
||||
if (!homeDir) return;
|
||||
|
||||
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
|
||||
|
||||
try {
|
||||
const file = await readFile(machineEnvFile, 'utf8');
|
||||
for (const rawLine of file.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
|
||||
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
||||
if (!matched) continue;
|
||||
|
||||
const [, key, rawValue] = matched;
|
||||
const value = rawValue.replace(/^["']|["']$/g, '');
|
||||
process.env[key] = value;
|
||||
}
|
||||
} catch {
|
||||
// start.ps1도 파일이 없으면 그냥 지나간다.
|
||||
}
|
||||
}
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
envFilePath: [
|
||||
resolve(__dirname, '../../project.env'),
|
||||
resolve(process.cwd(), 'apps/project.env'),
|
||||
resolve(process.cwd(), 'project.env'),
|
||||
],
|
||||
}),
|
||||
SecretModule,
|
||||
],
|
||||
providers: [ConnectionService],
|
||||
})
|
||||
class SeedModule {}
|
||||
|
||||
type SeedPlayer = {
|
||||
key: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
kakaoTalkNickname: string;
|
||||
profileIconId: number;
|
||||
main: Position;
|
||||
sub: Position;
|
||||
tier: {
|
||||
tier: string;
|
||||
rank: string;
|
||||
leaguePoints: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
};
|
||||
flex?: {
|
||||
tier: string;
|
||||
rank: string;
|
||||
leaguePoints: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
};
|
||||
masteries: ChampionMasteryEntry[];
|
||||
recentStatsSummary: RiotRecentStatsSummary;
|
||||
};
|
||||
|
||||
const DEV_COMMUNITY_NAME = '[DEV] Lolympus Test Community';
|
||||
const DEV_COMMUNITY_DESCRIPTION =
|
||||
'Frontend/Backend 통합 검증용으로 생성된 개발 커뮤니티입니다.';
|
||||
|
||||
const NOW = new Date();
|
||||
|
||||
const PLAYER_SEEDS: SeedPlayer[] = [
|
||||
{
|
||||
key: 'priri',
|
||||
gameName: '프리리',
|
||||
tagLine: 'KR1',
|
||||
kakaoTalkNickname: '프리리',
|
||||
profileIconId: 588,
|
||||
main: 'MID',
|
||||
sub: 'ADC',
|
||||
tier: {
|
||||
tier: 'DIAMOND',
|
||||
rank: 'IV',
|
||||
leaguePoints: 37,
|
||||
wins: 66,
|
||||
losses: 58,
|
||||
},
|
||||
flex: {
|
||||
tier: 'EMERALD',
|
||||
rank: 'I',
|
||||
leaguePoints: 54,
|
||||
wins: 31,
|
||||
losses: 22,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Syndra', championName: '신드라', level: 7, points: 124300 },
|
||||
{ championId: 'Ahri', championName: '아리', level: 7, points: 98200 },
|
||||
{ championId: 'Orianna', championName: '오리아나', level: 6, points: 63400 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 24,
|
||||
wins: 14,
|
||||
losses: 10,
|
||||
avgKills: 7.8,
|
||||
avgDeaths: 4.2,
|
||||
avgAssists: 6.7,
|
||||
avgCs: 188,
|
||||
mostPlayedChampionIds: ['Syndra', 'Ahri', 'Orianna'],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'hobul',
|
||||
gameName: '호호불어먹어요',
|
||||
tagLine: '0000',
|
||||
kakaoTalkNickname: '호호불',
|
||||
profileIconId: 7015,
|
||||
main: 'JGL',
|
||||
sub: 'TOP',
|
||||
tier: {
|
||||
tier: 'PLATINUM',
|
||||
rank: 'II',
|
||||
leaguePoints: 73,
|
||||
wins: 54,
|
||||
losses: 49,
|
||||
},
|
||||
flex: {
|
||||
tier: 'EMERALD',
|
||||
rank: 'III',
|
||||
leaguePoints: 22,
|
||||
wins: 14,
|
||||
losses: 10,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Viego', championName: '비에고', level: 7, points: 138200 },
|
||||
{ championId: 'LeeSin', championName: '리신', level: 6, points: 88700 },
|
||||
{ championId: 'Nidalee', championName: '니달리', level: 6, points: 64100 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 28,
|
||||
wins: 15,
|
||||
losses: 13,
|
||||
avgKills: 5.9,
|
||||
avgDeaths: 4.9,
|
||||
avgAssists: 9.1,
|
||||
avgCs: 151,
|
||||
mostPlayedChampionIds: ['Viego', 'LeeSin', 'Nidalee'],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'soda',
|
||||
gameName: '소다',
|
||||
tagLine: 'KR1',
|
||||
kakaoTalkNickname: '소다',
|
||||
profileIconId: 5186,
|
||||
main: 'TOP',
|
||||
sub: 'MID',
|
||||
tier: {
|
||||
tier: 'EMERALD',
|
||||
rank: 'I',
|
||||
leaguePoints: 18,
|
||||
wins: 49,
|
||||
losses: 41,
|
||||
},
|
||||
flex: {
|
||||
tier: 'PLATINUM',
|
||||
rank: 'I',
|
||||
leaguePoints: 64,
|
||||
wins: 20,
|
||||
losses: 14,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Jax', championName: '잭스', level: 7, points: 112400 },
|
||||
{ championId: 'Camille', championName: '카밀', level: 6, points: 76500 },
|
||||
{ championId: 'Gwen', championName: '그웬', level: 6, points: 58700 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 21,
|
||||
wins: 11,
|
||||
losses: 10,
|
||||
avgKills: 5.4,
|
||||
avgDeaths: 4.6,
|
||||
avgAssists: 5.2,
|
||||
avgCs: 201,
|
||||
mostPlayedChampionIds: ['Jax', 'Camille', 'Gwen'],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'inghoba',
|
||||
gameName: '잉호바',
|
||||
tagLine: 'KR1',
|
||||
kakaoTalkNickname: '잉호바',
|
||||
profileIconId: 7050,
|
||||
main: 'SUP',
|
||||
sub: 'MID',
|
||||
tier: {
|
||||
tier: 'DIAMOND',
|
||||
rank: 'III',
|
||||
leaguePoints: 41,
|
||||
wins: 72,
|
||||
losses: 60,
|
||||
},
|
||||
flex: {
|
||||
tier: 'MASTER',
|
||||
rank: '',
|
||||
leaguePoints: 121,
|
||||
wins: 19,
|
||||
losses: 11,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Thresh', championName: '쓰레쉬', level: 7, points: 187300 },
|
||||
{ championId: 'Nautilus', championName: '노틸러스', level: 7, points: 144800 },
|
||||
{ championId: 'Rakan', championName: '라칸', level: 6, points: 65300 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 32,
|
||||
wins: 19,
|
||||
losses: 13,
|
||||
avgKills: 2.5,
|
||||
avgDeaths: 4.3,
|
||||
avgAssists: 14.8,
|
||||
avgCs: 34,
|
||||
mostPlayedChampionIds: ['Thresh', 'Nautilus', 'Rakan'],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'tabkey',
|
||||
gameName: '잉호바탭키도둑',
|
||||
tagLine: 'Tab',
|
||||
kakaoTalkNickname: '탭키도둑',
|
||||
profileIconId: 5231,
|
||||
main: 'ADC',
|
||||
sub: 'SUP',
|
||||
tier: {
|
||||
tier: 'PLATINUM',
|
||||
rank: 'I',
|
||||
leaguePoints: 47,
|
||||
wins: 61,
|
||||
losses: 56,
|
||||
},
|
||||
flex: {
|
||||
tier: 'EMERALD',
|
||||
rank: 'IV',
|
||||
leaguePoints: 28,
|
||||
wins: 22,
|
||||
losses: 20,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Jinx', championName: '징크스', level: 7, points: 166100 },
|
||||
{ championId: 'KaiSa', championName: '카이사', level: 7, points: 139400 },
|
||||
{ championId: 'Ezreal', championName: '이즈리얼', level: 6, points: 90100 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 29,
|
||||
wins: 16,
|
||||
losses: 13,
|
||||
avgKills: 8.4,
|
||||
avgDeaths: 4.8,
|
||||
avgAssists: 6.1,
|
||||
avgCs: 213,
|
||||
mostPlayedChampionIds: ['Jinx', 'KaiSa', 'Ezreal'],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'osu',
|
||||
gameName: 'osu',
|
||||
tagLine: 'KR1',
|
||||
kakaoTalkNickname: 'osu',
|
||||
profileIconId: 7091,
|
||||
main: 'MID',
|
||||
sub: 'JGL',
|
||||
tier: {
|
||||
tier: 'EMERALD',
|
||||
rank: 'III',
|
||||
leaguePoints: 59,
|
||||
wins: 58,
|
||||
losses: 50,
|
||||
},
|
||||
flex: {
|
||||
tier: 'MASTER',
|
||||
rank: '',
|
||||
leaguePoints: 74,
|
||||
wins: 12,
|
||||
losses: 8,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Viktor', championName: '빅토르', level: 7, points: 172900 },
|
||||
{ championId: 'Hwei', championName: '흐웨이', level: 6, points: 94400 },
|
||||
{ championId: 'Taliyah', championName: '탈리야', level: 6, points: 55300 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 25,
|
||||
wins: 13,
|
||||
losses: 12,
|
||||
avgKills: 6.3,
|
||||
avgDeaths: 5.2,
|
||||
avgAssists: 7.7,
|
||||
avgCs: 198,
|
||||
mostPlayedChampionIds: ['Viktor', 'Hwei', 'Taliyah'],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'icequeen',
|
||||
gameName: 'IceQueen',
|
||||
tagLine: 'KR1',
|
||||
kakaoTalkNickname: '아이스퀸',
|
||||
profileIconId: 5102,
|
||||
main: 'ADC',
|
||||
sub: 'MID',
|
||||
tier: {
|
||||
tier: 'DIAMOND',
|
||||
rank: 'II',
|
||||
leaguePoints: 63,
|
||||
wins: 67,
|
||||
losses: 52,
|
||||
},
|
||||
flex: {
|
||||
tier: 'MASTER',
|
||||
rank: '',
|
||||
leaguePoints: 34,
|
||||
wins: 11,
|
||||
losses: 9,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Xayah', championName: '자야', level: 7, points: 154800 },
|
||||
{ championId: 'Zeri', championName: '제리', level: 7, points: 141900 },
|
||||
{ championId: 'Ashe', championName: '애쉬', level: 6, points: 59800 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 31,
|
||||
wins: 18,
|
||||
losses: 13,
|
||||
avgKills: 7.7,
|
||||
avgDeaths: 4.4,
|
||||
avgAssists: 7.2,
|
||||
avgCs: 226,
|
||||
mostPlayedChampionIds: ['Xayah', 'Zeri', 'Ashe'],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'jungler123',
|
||||
gameName: '정글러123',
|
||||
tagLine: 'KR3',
|
||||
kakaoTalkNickname: '정글러123',
|
||||
profileIconId: 4789,
|
||||
main: 'JGL',
|
||||
sub: 'SUP',
|
||||
tier: {
|
||||
tier: 'PLATINUM',
|
||||
rank: 'III',
|
||||
leaguePoints: 15,
|
||||
wins: 43,
|
||||
losses: 42,
|
||||
},
|
||||
flex: {
|
||||
tier: 'GOLD',
|
||||
rank: 'I',
|
||||
leaguePoints: 87,
|
||||
wins: 18,
|
||||
losses: 16,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'LeeSin', championName: '리신', level: 7, points: 201300 },
|
||||
{ championId: 'Viego', championName: '비에고', level: 6, points: 87600 },
|
||||
{ championId: 'Rengar', championName: '렝가', level: 6, points: 65400 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 38,
|
||||
wins: 18,
|
||||
losses: 20,
|
||||
avgKills: 5.4,
|
||||
avgDeaths: 5.8,
|
||||
avgAssists: 8.1,
|
||||
avgCs: 142,
|
||||
mostPlayedChampionIds: ['LeeSin', 'Viego', 'Rengar'],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'topsol',
|
||||
gameName: '탑솔장인',
|
||||
tagLine: 'KR1',
|
||||
kakaoTalkNickname: '탑솔장인',
|
||||
profileIconId: 5450,
|
||||
main: 'TOP',
|
||||
sub: 'JGL',
|
||||
tier: {
|
||||
tier: 'EMERALD',
|
||||
rank: 'II',
|
||||
leaguePoints: 46,
|
||||
wins: 57,
|
||||
losses: 44,
|
||||
},
|
||||
flex: {
|
||||
tier: 'PLATINUM',
|
||||
rank: 'II',
|
||||
leaguePoints: 34,
|
||||
wins: 21,
|
||||
losses: 19,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Jax', championName: '잭스', level: 7, points: 145600 },
|
||||
{ championId: 'Yorick', championName: '요릭', level: 7, points: 112400 },
|
||||
{ championId: 'Nasus', championName: '나서스', level: 6, points: 89300 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 47,
|
||||
wins: 27,
|
||||
losses: 20,
|
||||
avgKills: 5.6,
|
||||
avgDeaths: 3.9,
|
||||
avgAssists: 4.1,
|
||||
avgCs: 201,
|
||||
mostPlayedChampionIds: ['Jax', 'Yorick', 'Nasus'],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'supporter',
|
||||
gameName: '서폿장인',
|
||||
tagLine: '0001',
|
||||
kakaoTalkNickname: '서폿장인',
|
||||
profileIconId: 4900,
|
||||
main: 'SUP',
|
||||
sub: 'ADC',
|
||||
tier: {
|
||||
tier: 'DIAMOND',
|
||||
rank: 'IV',
|
||||
leaguePoints: 9,
|
||||
wins: 64,
|
||||
losses: 61,
|
||||
},
|
||||
flex: {
|
||||
tier: 'DIAMOND',
|
||||
rank: 'III',
|
||||
leaguePoints: 25,
|
||||
wins: 17,
|
||||
losses: 14,
|
||||
},
|
||||
masteries: [
|
||||
{ championId: 'Yuumi', championName: '유미', level: 7, points: 198700 },
|
||||
{ championId: 'Sona', championName: '소나', level: 7, points: 145200 },
|
||||
{ championId: 'Nami', championName: '나미', level: 6, points: 92100 },
|
||||
],
|
||||
recentStatsSummary: {
|
||||
games: 52,
|
||||
wins: 30,
|
||||
losses: 22,
|
||||
avgKills: 1.8,
|
||||
avgDeaths: 4.2,
|
||||
avgAssists: 16.3,
|
||||
avgCs: 25,
|
||||
mostPlayedChampionIds: ['Yuumi', 'Sona', 'Nami'],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function createPreferences(main: Position, sub: Position): PositionPreference[] {
|
||||
const rest = (['TOP', 'JGL', 'MID', 'ADC', 'SUP'] as Position[]).filter(
|
||||
(position) => position !== main && position !== sub,
|
||||
);
|
||||
|
||||
return [
|
||||
{ position: main, priority: 1 },
|
||||
{ position: sub, priority: 2 },
|
||||
...rest.map((position, index) => ({
|
||||
position,
|
||||
priority: index + 3,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
function createTier(
|
||||
queueType: string,
|
||||
tier: string,
|
||||
rank: string,
|
||||
leaguePoints: number,
|
||||
wins: number,
|
||||
losses: number,
|
||||
): TierInfo {
|
||||
return {
|
||||
queueType,
|
||||
tier,
|
||||
rank: rank || 'I',
|
||||
leaguePoints,
|
||||
wins,
|
||||
losses,
|
||||
fetchedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
function selectPrimaryTier(tiers: TierInfo[]) {
|
||||
return tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ?? tiers[0];
|
||||
}
|
||||
|
||||
function createRiotAccount(player: SeedPlayer) {
|
||||
const tiers = [
|
||||
createTier(
|
||||
'RANKED_SOLO_5x5',
|
||||
player.tier.tier,
|
||||
player.tier.rank,
|
||||
player.tier.leaguePoints,
|
||||
player.tier.wins,
|
||||
player.tier.losses,
|
||||
),
|
||||
];
|
||||
|
||||
if (player.flex) {
|
||||
tiers.push(
|
||||
createTier(
|
||||
'RANKED_FLEX_SR',
|
||||
player.flex.tier,
|
||||
player.flex.rank,
|
||||
player.flex.leaguePoints,
|
||||
player.flex.wins,
|
||||
player.flex.losses,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
puuid: `dev-seed-${player.key}-puuid`,
|
||||
gameName: player.gameName,
|
||||
tagLine: player.tagLine,
|
||||
profileIconId: player.profileIconId,
|
||||
revisionDate: Date.now(),
|
||||
summonerLevel: 200,
|
||||
isPrimary: true,
|
||||
tiers,
|
||||
tierHistory: [],
|
||||
matchIds: [],
|
||||
recentStatsSummary: player.recentStatsSummary,
|
||||
recentStatsFetchedAt: NOW,
|
||||
championMasteries: player.masteries,
|
||||
championMasteriesFetchedAt: NOW,
|
||||
championRecords: {},
|
||||
championRecordsFetchedAt: NOW,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
function createStaffRiotAccount(key: string, gameName: string, tagLine: string) {
|
||||
return {
|
||||
puuid: `dev-seed-${key}-puuid`,
|
||||
gameName,
|
||||
tagLine,
|
||||
profileIconId: 29,
|
||||
revisionDate: Date.now(),
|
||||
summonerLevel: 120,
|
||||
isPrimary: true,
|
||||
tiers: [createTier('RANKED_SOLO_5x5', 'GOLD', 'I', 75, 24, 19)],
|
||||
tierHistory: [],
|
||||
matchIds: [],
|
||||
recentStatsSummary: {
|
||||
games: 12,
|
||||
wins: 7,
|
||||
losses: 5,
|
||||
avgKills: 5.1,
|
||||
avgDeaths: 4.3,
|
||||
avgAssists: 7.4,
|
||||
avgCs: 167,
|
||||
mostPlayedChampionIds: ['Orianna', 'JarvanIV'],
|
||||
},
|
||||
recentStatsFetchedAt: NOW,
|
||||
championMasteries: [
|
||||
{ championId: 'Orianna', championName: '오리아나', level: 5, points: 18300 },
|
||||
{ championId: 'JarvanIV', championName: '자르반 4세', level: 5, points: 12600 },
|
||||
],
|
||||
championMasteriesFetchedAt: NOW,
|
||||
championRecords: {},
|
||||
championRecordsFetchedAt: NOW,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
function toMatchParticipant(user: {
|
||||
_id: mongoose.Types.ObjectId;
|
||||
riotAccounts: Array<{
|
||||
puuid: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
profileIconId: number;
|
||||
tiers: TierInfo[];
|
||||
}>;
|
||||
preferredPositions: PositionPreference[];
|
||||
}): MatchParticipant {
|
||||
const primary = user.riotAccounts[0];
|
||||
|
||||
return {
|
||||
userId: user._id,
|
||||
puuid: primary?.puuid,
|
||||
gameName: primary?.gameName,
|
||||
tagLine: primary?.tagLine,
|
||||
profileIconId: primary?.profileIconId,
|
||||
tier: primary ? selectPrimaryTier(primary.tiers) : undefined,
|
||||
preferredPositions: user.preferredPositions,
|
||||
joinedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await loadMachineEnvFile();
|
||||
|
||||
const app = await NestFactory.createApplicationContext(SeedModule, {
|
||||
logger: ['error', 'warn', 'log'],
|
||||
});
|
||||
|
||||
try {
|
||||
const connectionService = app.get(ConnectionService);
|
||||
const CommunityModel = await connectionService.getModel('community');
|
||||
const UserModel = await connectionService.getModel('user');
|
||||
const MatchModel = await connectionService.getModel('match');
|
||||
const AuctionModel = await connectionService.getModel('auction');
|
||||
|
||||
const existingCommunity = await CommunityModel.findOne({
|
||||
name: DEV_COMMUNITY_NAME,
|
||||
}).exec();
|
||||
|
||||
if (existingCommunity) {
|
||||
const existingMatches = await MatchModel.find({
|
||||
communityId: existingCommunity._id,
|
||||
})
|
||||
.select('_id')
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
const matchIds = existingMatches.map((match) => match._id);
|
||||
if (matchIds.length > 0) {
|
||||
await AuctionModel.deleteMany({ matchId: { $in: matchIds } }).exec();
|
||||
}
|
||||
|
||||
await MatchModel.deleteMany({ communityId: existingCommunity._id }).exec();
|
||||
await UserModel.deleteMany({ communityId: existingCommunity._id }).exec();
|
||||
await CommunityModel.deleteOne({ _id: existingCommunity._id }).exec();
|
||||
}
|
||||
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const ownerUserId = new mongoose.Types.ObjectId();
|
||||
const adminUserId = new mongoose.Types.ObjectId();
|
||||
|
||||
await CommunityModel.create({
|
||||
_id: communityId,
|
||||
name: DEV_COMMUNITY_NAME,
|
||||
description: DEV_COMMUNITY_DESCRIPTION,
|
||||
ownerUserId,
|
||||
});
|
||||
|
||||
const owner = {
|
||||
_id: ownerUserId,
|
||||
communityId,
|
||||
role: 'owner' as const,
|
||||
kakaoTalkId: 'dev-owner',
|
||||
kakaoTalkNickname: 'DevOwner',
|
||||
discordId: 'dev-owner-discord',
|
||||
discordNickname: 'DevOwner',
|
||||
riotAccounts: [createStaffRiotAccount('owner', 'DevOwner', 'KR1')],
|
||||
preferredPositions: createPreferences('MID', 'SUP'),
|
||||
isActivated: true,
|
||||
};
|
||||
|
||||
const admin = {
|
||||
_id: adminUserId,
|
||||
communityId,
|
||||
role: 'admin' as const,
|
||||
kakaoTalkId: 'dev-admin',
|
||||
kakaoTalkNickname: 'DevAdmin',
|
||||
discordId: 'dev-admin-discord',
|
||||
discordNickname: 'DevAdmin',
|
||||
riotAccounts: [createStaffRiotAccount('admin', 'DevAdmin', 'KR1')],
|
||||
preferredPositions: createPreferences('JGL', 'MID'),
|
||||
isActivated: true,
|
||||
};
|
||||
|
||||
const players = PLAYER_SEEDS.map((player) => ({
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
communityId,
|
||||
role: 'member' as const,
|
||||
kakaoTalkId: `seed-${player.key}`,
|
||||
kakaoTalkNickname: player.kakaoTalkNickname,
|
||||
discordId: `seed-${player.key}-discord`,
|
||||
discordNickname: player.gameName,
|
||||
riotAccounts: [createRiotAccount(player)],
|
||||
preferredPositions: createPreferences(player.main, player.sub),
|
||||
isActivated: true,
|
||||
}));
|
||||
|
||||
await UserModel.insertMany([owner, admin, ...players], { ordered: true });
|
||||
|
||||
const recruitingPlayers = players.slice(0, 6);
|
||||
const auctionPlayers = players;
|
||||
const finishedBlue = [
|
||||
{ user: players[0], assignedPosition: 'MID' as const, cost: 0 },
|
||||
{ user: players[2], assignedPosition: 'TOP' as const, cost: 320 },
|
||||
{ user: players[4], assignedPosition: 'ADC' as const, cost: 280 },
|
||||
{ user: players[7], assignedPosition: 'JGL' as const, cost: 190 },
|
||||
{ user: players[9], assignedPosition: 'SUP' as const, cost: 210 },
|
||||
];
|
||||
const finishedRed = [
|
||||
{ user: players[1], assignedPosition: 'JGL' as const, cost: 0 },
|
||||
{ user: players[3], assignedPosition: 'SUP' as const, cost: 240 },
|
||||
{ user: players[5], assignedPosition: 'MID' as const, cost: 250 },
|
||||
{ user: players[6], assignedPosition: 'ADC' as const, cost: 300 },
|
||||
{ user: players[8], assignedPosition: 'TOP' as const, cost: 220 },
|
||||
];
|
||||
|
||||
const recruitingMatchId = new mongoose.Types.ObjectId();
|
||||
const auctionMatchId = new mongoose.Types.ObjectId();
|
||||
const finishedMatchId = new mongoose.Types.ObjectId();
|
||||
|
||||
await MatchModel.insertMany([
|
||||
{
|
||||
_id: recruitingMatchId,
|
||||
communityId,
|
||||
hostUserId: ownerUserId,
|
||||
title: '쌀먹 내전',
|
||||
description: '통합 테스트용 모집 중 매치입니다.',
|
||||
mapId: 11,
|
||||
status: 'recruiting',
|
||||
scheduledAt: new Date('2026-04-27T12:00:00.000Z'),
|
||||
maxParticipants: 10,
|
||||
participants: recruitingPlayers.map(toMatchParticipant),
|
||||
teams: [],
|
||||
prizes: ['5명 추첨 커피', 'MVP: 스킨 선물'],
|
||||
notices: [
|
||||
'시작 10분 전까지 커스텀 방에 입장해주세요.',
|
||||
'개발용 시드 데이터입니다.',
|
||||
],
|
||||
schedule: [
|
||||
{ time: '20:50', label: '로비 오픈' },
|
||||
{ time: '21:00', label: '내전 시작' },
|
||||
],
|
||||
},
|
||||
{
|
||||
_id: auctionMatchId,
|
||||
communityId,
|
||||
hostUserId: ownerUserId,
|
||||
title: '롤림푸스 경매 테스트 매치',
|
||||
description: 'Socket.IO 경매 페이지 검증용으로 생성된 매치입니다.',
|
||||
mapId: 11,
|
||||
status: 'team-built',
|
||||
scheduledAt: new Date('2026-04-26T11:00:00.000Z'),
|
||||
maxParticipants: 10,
|
||||
participants: auctionPlayers.map(toMatchParticipant),
|
||||
teams: [
|
||||
{
|
||||
side: 'blue',
|
||||
name: '블루팀',
|
||||
captainUserId: players[0]._id,
|
||||
members: [
|
||||
{
|
||||
userId: players[0]._id,
|
||||
assignedPosition: 'MID',
|
||||
cost: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
side: 'red',
|
||||
name: '레드팀',
|
||||
captainUserId: players[1]._id,
|
||||
members: [
|
||||
{
|
||||
userId: players[1]._id,
|
||||
assignedPosition: 'JGL',
|
||||
cost: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
prizes: ['우승팀 햄버거 세트'],
|
||||
notices: ['현재 경매 진행 중인 테스트 매치입니다.'],
|
||||
schedule: [
|
||||
{ time: '19:30', label: '디스코드 집합' },
|
||||
{ time: '19:45', label: '경매 시작' },
|
||||
],
|
||||
},
|
||||
{
|
||||
_id: finishedMatchId,
|
||||
communityId,
|
||||
hostUserId: ownerUserId,
|
||||
title: '시즌 4 준결승',
|
||||
description: '완료된 매치 UI 확인용 더미 경기 결과입니다.',
|
||||
mapId: 11,
|
||||
status: 'finished',
|
||||
scheduledAt: new Date('2026-04-20T11:00:00.000Z'),
|
||||
maxParticipants: 10,
|
||||
participants: players.map(toMatchParticipant),
|
||||
teams: [
|
||||
{
|
||||
side: 'blue',
|
||||
name: '블루팀',
|
||||
captainUserId: players[0]._id,
|
||||
members: finishedBlue.map((member) => ({
|
||||
userId: member.user._id,
|
||||
assignedPosition: member.assignedPosition,
|
||||
cost: member.cost,
|
||||
})),
|
||||
},
|
||||
{
|
||||
side: 'red',
|
||||
name: '레드팀',
|
||||
captainUserId: players[1]._id,
|
||||
members: finishedRed.map((member) => ({
|
||||
userId: member.user._id,
|
||||
assignedPosition: member.assignedPosition,
|
||||
cost: member.cost,
|
||||
})),
|
||||
},
|
||||
],
|
||||
result: {
|
||||
winnerSide: 'blue',
|
||||
blueScore: 2,
|
||||
redScore: 1,
|
||||
mvpUserId: players[0]._id,
|
||||
riotMatchIds: ['KR_DEV_0001', 'KR_DEV_0002', 'KR_DEV_0003'],
|
||||
},
|
||||
prizes: ['1등 팀: RP 10,000 지급', 'MVP: 프리리'],
|
||||
notices: [],
|
||||
schedule: [],
|
||||
},
|
||||
]);
|
||||
|
||||
const auctionOrder = auctionPlayers.slice(2).map((player) => {
|
||||
const primary = player.riotAccounts[0];
|
||||
|
||||
return {
|
||||
userId: player._id,
|
||||
puuid: primary.puuid,
|
||||
gameName: primary.gameName,
|
||||
tagLine: primary.tagLine,
|
||||
profileIconId: primary.profileIconId,
|
||||
preferredPositions: player.preferredPositions,
|
||||
tiers: primary.tiers,
|
||||
masteries: primary.championMasteries,
|
||||
recentStatsSummary: primary.recentStatsSummary,
|
||||
};
|
||||
});
|
||||
|
||||
await AuctionModel.create({
|
||||
matchId: auctionMatchId,
|
||||
phase: 'presenting',
|
||||
teams: [
|
||||
{
|
||||
side: 'blue',
|
||||
captainUserId: players[0]._id,
|
||||
points: 1000,
|
||||
members: [],
|
||||
},
|
||||
{
|
||||
side: 'red',
|
||||
captainUserId: players[1]._id,
|
||||
points: 1000,
|
||||
members: [],
|
||||
},
|
||||
],
|
||||
order: auctionOrder,
|
||||
currentIndex: 0,
|
||||
bids: [],
|
||||
currentBid: 0,
|
||||
maxTimerSeconds: 30,
|
||||
initialPoints: 1000,
|
||||
startedAt: NOW,
|
||||
});
|
||||
|
||||
const summary = {
|
||||
communityId: communityId.toString(),
|
||||
ownerUserId: ownerUserId.toString(),
|
||||
adminUserId: adminUserId.toString(),
|
||||
recruitingMatchId: recruitingMatchId.toString(),
|
||||
auctionMatchId: auctionMatchId.toString(),
|
||||
finishedMatchId: finishedMatchId.toString(),
|
||||
playerUserIds: players.map((player) => ({
|
||||
userId: player._id.toString(),
|
||||
gameName: player.riotAccounts[0].gameName,
|
||||
})),
|
||||
};
|
||||
|
||||
console.log('\n[seed:dev] Dev seed completed.\n');
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
console.log(
|
||||
`\napps/web/.env.development 에 아래 값을 넣으면 됩니다:\nVITE_DEFAULT_COMMUNITY_ID=${summary.communityId}\n`,
|
||||
);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
console.error('\n[seed:dev] Failed to seed database.\n');
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in new issue
Block a user