.
This commit is contained in:
1 parent
30dfb7ce58
commit
5af2c80cd1
33 files changed
+3806
-1440
No files matched your search
@@ -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 {}
|
||||
Reference in new issue
Block a user