diff --git a/apps/api/src/modules/analysis/analysis-read.service.ts b/apps/api/src/modules/analysis/analysis-read.service.ts index dec496c..adb1658 100644 --- a/apps/api/src/modules/analysis/analysis-read.service.ts +++ b/apps/api/src/modules/analysis/analysis-read.service.ts @@ -3,6 +3,7 @@ import { FEATURE_SCHEMA_VERSION, METRICS, type AnalysisJobStatusDto, + type MentorMatchesDto, type MetricValueDto, type PlayerAnalysisDto, } from '@persona-lenz/shared'; @@ -13,6 +14,8 @@ import type { PlayerProfile, TierInfo, } from '../global/database/schemas'; +import { MentorMatchService } from './mentor-match.service'; +import type { MentorMatch } from './analysis.types'; type JobStatusRecord = Pick< AnalysisJob, @@ -24,6 +27,8 @@ type AccountSummaryRecord = Pick< 'gameName' | 'profileIconId' | 'tagLine' | 'tiers' >; +type MentorAccountRecord = Pick; + type PlayerProfileRecord = Pick< PlayerProfile, | 'championPool' @@ -38,7 +43,10 @@ type PlayerProfileRecord = Pick< @Injectable() export class AnalysisReadService { - constructor(private readonly connectionService: ConnectionService) {} + constructor( + private readonly connectionService: ConnectionService, + private readonly mentorMatchService?: MentorMatchService, + ) {} public async getJobStatus(jobId: string): Promise { const analysisJobModel = @@ -105,6 +113,34 @@ export class AnalysisReadService { }; } + public async getMentorMatches( + puuid: string, + queueId: number, + limit: number, + ): Promise { + if (!this.mentorMatchService) { + throw new Error('MentorMatchService is not configured.'); + } + + const mentorMatchesResult = await this.mentorMatchService.findMentorMatches( + puuid, + queueId, + limit, + ); + const mentorAccountsByPuuid = await this.findMentorAccounts( + mentorMatchesResult.matches.map((match) => match.puuid), + ); + + return { + puuid: mentorMatchesResult.puuid, + queueId: mentorMatchesResult.queueId, + profileUpdatedAt: mentorMatchesResult.profileUpdatedAt.toISOString(), + matches: mentorMatchesResult.matches.map((match) => + this.toMentorMatchDto(match, mentorAccountsByPuuid.get(match.puuid)), + ), + }; + } + private async findAccount( puuid: string, ): Promise { @@ -112,6 +148,21 @@ export class AnalysisReadService { return accountModel.findOne({ puuid }).lean().exec(); } + private async findMentorAccounts( + puuids: string[], + ): Promise> { + const uniquePuuids = Array.from(new Set(puuids)); + if (uniquePuuids.length === 0) return new Map(); + + const accountModel = await this.connectionService.getModel('account'); + const accounts = await accountModel + .find({ puuid: { $in: uniquePuuids } }) + .lean() + .exec(); + + return new Map(accounts.map((account) => [account.puuid, account])); + } + private async findPlayerProfile( puuid: string, queueId: number, @@ -170,6 +221,31 @@ export class AnalysisReadService { }; } + private toMentorMatchDto( + match: MentorMatch, + account: MentorAccountRecord | undefined, + ): MentorMatchesDto['matches'][number] { + return { + puuid: match.puuid, + riotId: account + ? { + gameName: account.gameName, + tagLine: account.tagLine, + } + : null, + similarityScore: match.similarityScore, + finalScore: match.finalScore, + tier: match.tier, + division: match.division, + leaguePoints: match.leaguePoints, + mainRole: match.mainRole, + mainChampions: match.mainChampions, + sampleGameCount: match.sampleGameCount, + similarMetrics: match.similarMetrics, + gapMetrics: match.gapMetrics, + }; + } + private publicJobError(error: string | undefined): string | null { if (!error) return null; if ( diff --git a/apps/api/src/modules/analysis/analysis.controller.ts b/apps/api/src/modules/analysis/analysis.controller.ts index 2378661..c968412 100644 --- a/apps/api/src/modules/analysis/analysis.controller.ts +++ b/apps/api/src/modules/analysis/analysis.controller.ts @@ -12,6 +12,7 @@ import { import type { AnalysisJobStatusDto, AnalysisRequestAcceptedDto, + MentorMatchesDto, PlayerAnalysisDto, } from '@persona-lenz/shared'; import { @@ -69,6 +70,19 @@ export class AnalysisController { ); } + @Get('players/:puuid/mentor-matches') + public async getMentorMatches( + @Param('puuid') puuid: string, + @Query('queueId') rawQueueId?: string, + @Query('limit') rawLimit?: string, + ): Promise { + return this.analysisReadService.getMentorMatches( + this.parsePuuid(puuid), + this.parseQueueId(rawQueueId), + this.parseMentorMatchLimit(rawLimit), + ); + } + private parseAnalysisRequest(body: unknown): UserAnalysisJobData { const record = this.requireRecord(body); const gameName = this.parseTrimmedString( @@ -151,6 +165,15 @@ export class AnalysisController { return queueId; } + private parseMentorMatchLimit(value?: string): number { + if (value === undefined) return 10; + const limit = Number(value); + if (!Number.isInteger(limit) || limit < 1) { + throw new BadRequestException('limit is out of range.'); + } + return Math.min(limit, 10); + } + private resolveClientKey(request: Request): string { return request.ip || request.socket.remoteAddress || 'unknown-client'; } diff --git a/apps/api/test/app.e2e-spec.ts b/apps/api/test/app.e2e-spec.ts index 3ecb087..0023a07 100644 --- a/apps/api/test/app.e2e-spec.ts +++ b/apps/api/test/app.e2e-spec.ts @@ -3,6 +3,7 @@ import { Test, TestingModule } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import { FEATURE_SCHEMA_VERSION, + type MentorMatchesDto, type PlayerAnalysisDto, } from '@persona-lenz/shared'; import request from 'supertest'; @@ -10,7 +11,11 @@ import { App } from 'supertest/types'; import { configureApp } from './../src/app.setup'; import { AppModule } from './../src/app.module'; import { AnalysisQueueService } from './../src/modules/analysis/analysis-queue.service'; -import { ANALYSIS_QUEUE_NAME } from './../src/modules/analysis/analysis.constants'; +import { + ANALYSIS_QUEUE_NAME, + SEED_COLLECTION_QUEUE_NAME, +} from './../src/modules/analysis/analysis.constants'; +import { MentorMatchService } from './../src/modules/analysis/mentor-match.service'; import { ConnectionService } from './../src/modules/global/database/connection.service'; import { REDIS_CLIENT } from './../src/modules/global/redis/redis.constants'; import { SecretService } from './../src/modules/global/secret/secret.service'; @@ -20,6 +25,9 @@ describe('AppController (e2e)', () => { let analysisQueueService: { enqueueUserAnalysis: jest.Mock; }; + let mentorMatchService: { + findMentorMatches: jest.Mock; + }; let connectionService: { getModel: jest.Mock; }; @@ -36,6 +44,9 @@ describe('AppController (e2e)', () => { analysisQueueService = { enqueueUserAnalysis: jest.fn(), }; + mentorMatchService = { + findMentorMatches: jest.fn(), + }; connectionService = { getModel: jest.fn(), }; @@ -46,6 +57,8 @@ describe('AppController (e2e)', () => { .useValue(connectionService) .overrideProvider(AnalysisQueueService) .useValue(analysisQueueService) + .overrideProvider(MentorMatchService) + .useValue(mentorMatchService) .overrideProvider(SecretService) .useValue({ get: jest.fn((key: string) => { @@ -65,6 +78,10 @@ describe('AppController (e2e)', () => { .useValue({ add: jest.fn(), }) + .overrideProvider(getQueueToken(SEED_COLLECTION_QUEUE_NAME)) + .useValue({ + add: jest.fn(), + }) .compile(); app = moduleFixture.createNestApplication(); @@ -334,6 +351,7 @@ describe('AppController (e2e)', () => { expect(profileFindOne).toHaveBeenCalledWith({ puuid: 'target-puuid', queueId: 420, + featureSchemaVersion: FEATURE_SCHEMA_VERSION, }); expect(responseBody).toEqual({ account: { @@ -410,6 +428,105 @@ describe('AppController (e2e)', () => { }); }); + it('/api/players/:puuid/mentor-matches (GET) returns mentor matches with display Riot IDs', async () => { + mentorMatchService.findMentorMatches.mockResolvedValue({ + puuid: 'target-puuid', + queueId: 420, + profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'), + matches: [ + { + puuid: 'mentor-puuid', + similarityScore: 0.87, + finalScore: 0.81, + tier: 'CHALLENGER', + leaguePoints: 900, + mainRole: 'MIDDLE', + mainChampions: [{ championId: 103, games: 20, wins: 14 }], + sampleGameCount: 40, + similarMetrics: [ + { + metricId: 'kda', + currentValue: 0.3, + mentorValue: 0.31, + absoluteGap: 0.01, + }, + ], + gapMetrics: [ + { + metricId: 'goldPerMin', + currentValue: 0.5, + mentorValue: 0.8, + mentorAdvantage: 0.3, + }, + ], + }, + ], + }); + const accountFind = jest.fn(() => + createLeanExec([ + { + puuid: 'mentor-puuid', + gameName: '프리리', + tagLine: 'KR1', + }, + ]), + ); + connectionService.getModel.mockResolvedValue({ + find: accountFind, + }); + + const response = await request(app.getHttpServer()) + .get('/api/players/target-puuid/mentor-matches?limit=3') + .expect(200); + const responseBody = response.body as MentorMatchesDto; + + expect(mentorMatchService.findMentorMatches).toHaveBeenCalledWith( + 'target-puuid', + 420, + 3, + ); + expect(accountFind).toHaveBeenCalledWith({ + puuid: { $in: ['mentor-puuid'] }, + }); + expect(responseBody).toEqual({ + puuid: 'target-puuid', + queueId: 420, + profileUpdatedAt: '2026-07-02T00:00:00.000Z', + matches: [ + { + puuid: 'mentor-puuid', + riotId: { + gameName: '프리리', + tagLine: 'KR1', + }, + similarityScore: 0.87, + finalScore: 0.81, + tier: 'CHALLENGER', + leaguePoints: 900, + mainRole: 'MIDDLE', + mainChampions: [{ championId: 103, games: 20, wins: 14 }], + sampleGameCount: 40, + similarMetrics: [ + { + metricId: 'kda', + currentValue: 0.3, + mentorValue: 0.31, + absoluteGap: 0.01, + }, + ], + gapMetrics: [ + { + metricId: 'goldPerMin', + currentValue: 0.5, + mentorValue: 0.8, + mentorAdvantage: 0.3, + }, + ], + }, + ], + }); + }); + afterEach(async () => { await app.close(); }); diff --git a/packages/shared/src/dto/analysis.dto.ts b/packages/shared/src/dto/analysis.dto.ts index a973bcd..3e46ff2 100644 --- a/packages/shared/src/dto/analysis.dto.ts +++ b/packages/shared/src/dto/analysis.dto.ts @@ -96,3 +96,44 @@ export interface PlayerAnalysisDto { weaknesses: MetricValueDto[]; updatedAt: string; } + +export interface MentorRiotIdDto { + gameName: string; + tagLine: string; +} + +export interface SimilarMentorMetricDto { + metricId: MetricId; + currentValue: number; + mentorValue: number; + absoluteGap: number; +} + +export interface GapMentorMetricDto { + metricId: MetricId; + currentValue: number; + mentorValue: number; + mentorAdvantage: number; +} + +export interface MentorMatchDto { + puuid: string; + riotId: MentorRiotIdDto | null; + similarityScore: number; + finalScore: number; + tier?: string; + division?: string; + leaguePoints?: number; + mainRole: Role; + mainChampions: ChampionPoolEntryDto[]; + sampleGameCount: number; + similarMetrics: SimilarMentorMetricDto[]; + gapMetrics: GapMentorMetricDto[]; +} + +export interface MentorMatchesDto { + puuid: string; + queueId: number; + profileUpdatedAt: string; + matches: MentorMatchDto[]; +}