import { Injectable } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { MatchStats, MatchStatsDocument } from '../global/database/schema'; @Injectable() export class MatchStatsRepository { constructor(private readonly connectionService: ConnectionService) {} public async upsert( fragment: Omit, ): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); await MatchStatsModel.updateOne( { matchId: fragment.matchId }, { $set: fragment }, { upsert: true }, ).exec(); } public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); await MatchStatsModel.deleteOne({ matchId }).exec(); } public async deleteByMatches( matchIds: mongoose.Types.ObjectId[], ): Promise { if (matchIds.length === 0) return; const MatchStatsModel = await this.connectionService.getModel('matchStats'); await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec(); } public async findByMatch( matchId: mongoose.Types.ObjectId, ): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); return MatchStatsModel.findOne({ matchId }).exec(); } public async findByCommunity(params: { communityId: mongoose.Types.ObjectId; fromGameCreation?: number; toGameCreation?: number; limit?: number; }): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); const filter: Record = { communityId: params.communityId, }; if (params.fromGameCreation !== undefined) { filter.gameCreationMax = { $gte: params.fromGameCreation }; } if (params.toGameCreation !== undefined) { filter.gameCreationMin = { $lte: params.toGameCreation }; } return MatchStatsModel.find(filter) .sort({ scheduledAt: -1 }) .limit(params.limit ?? 300) .exec(); } public async findByUser(params: { communityId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; fromGameCreation?: number; toGameCreation?: number; }): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); const filter: Record = { communityId: params.communityId, userIds: params.userId, }; if (params.fromGameCreation !== undefined) { filter.gameCreationMax = { $gte: params.fromGameCreation }; } if (params.toGameCreation !== undefined) { filter.gameCreationMin = { $lte: params.toGameCreation }; } return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec(); } }