feat(api): enrich Riot accounts
This commit is contained in:
1 parent
463c839782
commit
d6f52a8b15
3 files changed
+991
No files matched your search
@@ -0,0 +1,494 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
createEmptyRiotRecentStatsSummary,
|
||||
type RiotRecentStatsSummary,
|
||||
} from '../global/database/schema';
|
||||
import { RiotAccountEnrichmentService } from './riot-account-enrichment.service';
|
||||
import { RiotAccountService } from './riot-account.service';
|
||||
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
|
||||
import { RiotApiError } from './riot.client.service';
|
||||
import { RiotLeagueService } from './riot-league.service';
|
||||
import { RiotRecentMatchesService } from './riot-recent-matches.service';
|
||||
import { RiotRecentStatsService } from './riot-recent-stats.service';
|
||||
import { RiotSummonerService } from './riot-summoner.service';
|
||||
|
||||
interface FakeAccount {
|
||||
puuid: string;
|
||||
profileIconId: number;
|
||||
revisionDate: number;
|
||||
summonerLevel: number;
|
||||
matchIds: string[];
|
||||
matchIdsFetchedAt?: Date;
|
||||
recentStatsSummary?: RiotRecentStatsSummary;
|
||||
recentStatsFetchedAt?: Date;
|
||||
tiers: Array<{
|
||||
leagueId: string;
|
||||
queueType: string;
|
||||
tier: string;
|
||||
rank: string;
|
||||
puuid: string;
|
||||
leaguePoints: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
fetchedAt: Date;
|
||||
}>;
|
||||
tierHistory: Array<{
|
||||
queueType: string;
|
||||
tier: string;
|
||||
rank?: string;
|
||||
leaguePoints?: number;
|
||||
wins?: number;
|
||||
losses?: number;
|
||||
recordedAt: Date;
|
||||
}>;
|
||||
championMasteries: Array<{
|
||||
puuid: string;
|
||||
championId: number;
|
||||
championLevel: number;
|
||||
championPoints: number;
|
||||
}>;
|
||||
championMasteriesFetchedAt?: Date;
|
||||
championRecords: Record<string, unknown>;
|
||||
championRecordsFetchedAt?: Date;
|
||||
}
|
||||
|
||||
function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
|
||||
return {
|
||||
puuid: 'puuid-1',
|
||||
profileIconId: 0,
|
||||
revisionDate: 0,
|
||||
summonerLevel: 0,
|
||||
matchIds: [],
|
||||
tiers: [],
|
||||
tierHistory: [],
|
||||
championMasteries: [],
|
||||
championRecords: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeUser(account: FakeAccount) {
|
||||
const _id = new mongoose.Types.ObjectId();
|
||||
const save = jest.fn().mockResolvedValue(undefined);
|
||||
return {
|
||||
_id,
|
||||
riotAccounts: [account],
|
||||
save,
|
||||
};
|
||||
}
|
||||
|
||||
function makeService(overrides?: {
|
||||
user?: any;
|
||||
account?: Partial<RiotAccountService>;
|
||||
summoner?: Partial<RiotSummonerService>;
|
||||
league?: Partial<RiotLeagueService>;
|
||||
mastery?: Partial<RiotChampionMasteryService>;
|
||||
recentMatches?: Partial<RiotRecentMatchesService>;
|
||||
recentStats?: Partial<RiotRecentStatsService>;
|
||||
}) {
|
||||
const user = overrides?.user;
|
||||
const userFindById = jest.fn().mockReturnValue({
|
||||
exec: () => Promise.resolve(user ?? null),
|
||||
});
|
||||
const communityFindById = jest.fn().mockReturnValue({
|
||||
select: () => ({
|
||||
lean: () => ({
|
||||
exec: () =>
|
||||
Promise.resolve({
|
||||
riotPlatform: 'kr',
|
||||
riotRegion: 'asia',
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (modelName: string) => {
|
||||
if (modelName === 'user') {
|
||||
return { findById: userFindById };
|
||||
}
|
||||
if (modelName === 'community') {
|
||||
return { findById: communityFindById };
|
||||
}
|
||||
throw new Error(`Unexpected model: ${modelName}`);
|
||||
}),
|
||||
} as unknown as ConnectionService;
|
||||
|
||||
const summonerService = {
|
||||
getByPuuid: jest.fn(),
|
||||
...overrides?.summoner,
|
||||
} as unknown as RiotSummonerService;
|
||||
const accountService = {
|
||||
getRegionByPuuid: jest.fn(),
|
||||
...overrides?.account,
|
||||
} as unknown as RiotAccountService;
|
||||
const leagueService = {
|
||||
getEntriesByPuuid: jest.fn(),
|
||||
...overrides?.league,
|
||||
} as unknown as RiotLeagueService;
|
||||
const masteryService = {
|
||||
getTopByPuuid: jest.fn(),
|
||||
...overrides?.mastery,
|
||||
} as unknown as RiotChampionMasteryService;
|
||||
const recentMatchesService = {
|
||||
syncRecentMatches: jest.fn().mockResolvedValue([]),
|
||||
loadFromDb: jest.fn().mockResolvedValue([]),
|
||||
...overrides?.recentMatches,
|
||||
} as unknown as RiotRecentMatchesService;
|
||||
const recentStatsService = {
|
||||
computeSummary: jest
|
||||
.fn()
|
||||
.mockReturnValue(createEmptyRiotRecentStatsSummary()),
|
||||
...overrides?.recentStats,
|
||||
} as unknown as RiotRecentStatsService;
|
||||
|
||||
const service = new RiotAccountEnrichmentService(
|
||||
connectionService,
|
||||
accountService,
|
||||
summonerService,
|
||||
leagueService,
|
||||
masteryService,
|
||||
recentMatchesService,
|
||||
recentStatsService,
|
||||
);
|
||||
return {
|
||||
service,
|
||||
user,
|
||||
accountService,
|
||||
summonerService,
|
||||
leagueService,
|
||||
masteryService,
|
||||
recentMatchesService,
|
||||
recentStatsService,
|
||||
};
|
||||
}
|
||||
|
||||
describe('RiotAccountEnrichmentService', () => {
|
||||
it('returns failed for unknown user', async () => {
|
||||
const { service } = makeService();
|
||||
const result = await service.enrichRiotAccount({
|
||||
userId: new mongoose.Types.ObjectId(),
|
||||
puuid: 'puuid-1',
|
||||
});
|
||||
expect(result.summoner).toBe('failed');
|
||||
expect(result.recentMatches).toBe('failed');
|
||||
expect(result.account).toBeNull();
|
||||
});
|
||||
|
||||
it('fills summoner / league / mastery on first attach (force)', async () => {
|
||||
const account = makeAccount();
|
||||
const user = makeUser(account);
|
||||
const {
|
||||
service,
|
||||
summonerService,
|
||||
leagueService,
|
||||
masteryService,
|
||||
recentMatchesService,
|
||||
recentStatsService,
|
||||
} =
|
||||
makeService({
|
||||
user,
|
||||
summoner: {
|
||||
getByPuuid: jest.fn().mockResolvedValue({
|
||||
puuid: 'puuid-1',
|
||||
profileIconId: 588,
|
||||
revisionDate: 1776977597000,
|
||||
summonerLevel: 529,
|
||||
}),
|
||||
} as Partial<RiotSummonerService>,
|
||||
league: {
|
||||
getEntriesByPuuid: jest.fn().mockResolvedValue([
|
||||
{
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'EMERALD',
|
||||
rank: 'I',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 75,
|
||||
wins: 160,
|
||||
losses: 148,
|
||||
},
|
||||
]),
|
||||
} as Partial<RiotLeagueService>,
|
||||
mastery: {
|
||||
getTopByPuuid: jest.fn().mockResolvedValue([
|
||||
{
|
||||
puuid: 'puuid-1',
|
||||
championId: 7,
|
||||
championLevel: 70,
|
||||
championPoints: 742560,
|
||||
},
|
||||
]),
|
||||
} as Partial<RiotChampionMasteryService>,
|
||||
recentMatches: {
|
||||
syncRecentMatches: jest.fn().mockResolvedValue([]),
|
||||
loadFromDb: jest.fn().mockResolvedValue([
|
||||
{ matchId: 'KR_1', raw: {} },
|
||||
{ matchId: 'KR_2', raw: {} },
|
||||
]),
|
||||
} as Partial<RiotRecentMatchesService>,
|
||||
recentStats: {
|
||||
computeSummary: jest.fn().mockReturnValue({
|
||||
overall: {
|
||||
games: 2,
|
||||
wins: 1,
|
||||
losses: 1,
|
||||
avgKills: 5.5,
|
||||
avgDeaths: 2.5,
|
||||
avgAssists: 7,
|
||||
avgCs: 175,
|
||||
avgCsPerMin: 6.4,
|
||||
mostPlayedChampionIds: [7, 103],
|
||||
},
|
||||
byLane: {},
|
||||
}),
|
||||
} as Partial<RiotRecentStatsService>,
|
||||
});
|
||||
|
||||
const result = await service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
options: { force: true },
|
||||
});
|
||||
|
||||
expect(result.summoner).toBe('updated');
|
||||
expect(result.league).toBe('updated');
|
||||
expect(result.masteries).toBe('updated');
|
||||
expect(result.recentMatches).toBe('updated');
|
||||
expect(account.profileIconId).toBe(588);
|
||||
expect(account.summonerLevel).toBe(529);
|
||||
expect(account.matchIds).toEqual(['KR_1', 'KR_2']);
|
||||
expect(account.recentStatsSummary).toMatchObject({
|
||||
overall: {
|
||||
games: 2,
|
||||
wins: 1,
|
||||
losses: 1,
|
||||
avgKills: 5.5,
|
||||
avgDeaths: 2.5,
|
||||
avgAssists: 7,
|
||||
avgCs: 175,
|
||||
avgCsPerMin: 6.4,
|
||||
mostPlayedChampionIds: [7, 103],
|
||||
},
|
||||
});
|
||||
expect(account.tiers).toHaveLength(1);
|
||||
expect(account.tiers[0]).toMatchObject({
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'EMERALD',
|
||||
rank: 'I',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 75,
|
||||
});
|
||||
expect(account.tierHistory).toHaveLength(1);
|
||||
expect(account.tierHistory[0]).toMatchObject({
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'EMERALD',
|
||||
rank: 'I',
|
||||
leaguePoints: 75,
|
||||
wins: 160,
|
||||
losses: 148,
|
||||
});
|
||||
expect(account.championMasteries).toEqual([
|
||||
{
|
||||
puuid: 'puuid-1',
|
||||
championId: 7,
|
||||
championLevel: 70,
|
||||
championPoints: 742560,
|
||||
},
|
||||
]);
|
||||
expect(account.championRecords).toEqual({});
|
||||
expect(user.save).toHaveBeenCalledTimes(1);
|
||||
expect(summonerService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
|
||||
platform: 'kr',
|
||||
});
|
||||
expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', {
|
||||
platform: 'kr',
|
||||
});
|
||||
expect(masteryService.getTopByPuuid).toHaveBeenCalledWith('puuid-1', {
|
||||
platform: 'kr',
|
||||
count: 10,
|
||||
});
|
||||
expect(recentMatchesService.syncRecentMatches).toHaveBeenCalledWith({
|
||||
puuid: 'puuid-1',
|
||||
region: 'asia',
|
||||
limit: 20,
|
||||
});
|
||||
expect(recentStatsService.computeSummary).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips fresh data when within TTL and not forced', async () => {
|
||||
const recent = new Date(Date.now() - 60_000);
|
||||
const account = makeAccount({
|
||||
profileIconId: 1,
|
||||
revisionDate: Date.now() - 60_000,
|
||||
summonerLevel: 100,
|
||||
tiers: [
|
||||
{
|
||||
leagueId: 'L1',
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
tier: 'GOLD',
|
||||
rank: 'II',
|
||||
puuid: 'puuid-1',
|
||||
leaguePoints: 1,
|
||||
wins: 1,
|
||||
losses: 1,
|
||||
fetchedAt: recent,
|
||||
},
|
||||
],
|
||||
championMasteriesFetchedAt: recent,
|
||||
recentStatsFetchedAt: recent,
|
||||
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
|
||||
});
|
||||
const user = makeUser(account);
|
||||
const summoner = jest.fn();
|
||||
const league = jest.fn();
|
||||
const mastery = jest.fn();
|
||||
const { service } = makeService({
|
||||
user,
|
||||
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
|
||||
league: {
|
||||
getEntriesByPuuid: league,
|
||||
} as Partial<RiotLeagueService>,
|
||||
mastery: {
|
||||
getTopByPuuid: mastery,
|
||||
} as Partial<RiotChampionMasteryService>,
|
||||
});
|
||||
|
||||
const result = await service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
});
|
||||
|
||||
expect(result.summoner).toBe('fresh');
|
||||
expect(result.league).toBe('fresh');
|
||||
expect(result.masteries).toBe('fresh');
|
||||
expect(result.recentMatches).toBe('fresh');
|
||||
expect(summoner).not.toHaveBeenCalled();
|
||||
expect(league).not.toHaveBeenCalled();
|
||||
expect(mastery).not.toHaveBeenCalled();
|
||||
expect(user.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('records failed for individual failing fetches but updates the rest', async () => {
|
||||
const account = makeAccount();
|
||||
const user = makeUser(account);
|
||||
const { service } = makeService({
|
||||
user,
|
||||
summoner: {
|
||||
getByPuuid: jest.fn().mockRejectedValue(new Error('boom')),
|
||||
} as Partial<RiotSummonerService>,
|
||||
league: {
|
||||
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<RiotLeagueService>,
|
||||
mastery: {
|
||||
getTopByPuuid: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<RiotChampionMasteryService>,
|
||||
});
|
||||
|
||||
const result = await service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
options: { force: true },
|
||||
});
|
||||
expect(result.summoner).toBe('failed');
|
||||
expect(result.league).toBe('updated');
|
||||
expect(result.masteries).toBe('updated');
|
||||
expect(result.recentMatches).toBe('updated');
|
||||
expect(user.save).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retries summoner lookup with region/by-puuid platform on 404', async () => {
|
||||
const account = makeAccount();
|
||||
const user = makeUser(account);
|
||||
const summoner = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new RiotApiError('not found', 404, 'url'))
|
||||
.mockResolvedValueOnce({
|
||||
puuid: 'puuid-1',
|
||||
profileIconId: 100,
|
||||
revisionDate: 1776977597000,
|
||||
summonerLevel: 30,
|
||||
});
|
||||
const region = jest.fn().mockResolvedValue({
|
||||
puuid: 'puuid-1',
|
||||
game: 'lol',
|
||||
region: 'jp1',
|
||||
});
|
||||
const league = jest.fn().mockResolvedValue([]);
|
||||
const mastery = jest.fn().mockResolvedValue([]);
|
||||
const { service } = makeService({
|
||||
user,
|
||||
account: { getRegionByPuuid: region } as Partial<RiotAccountService>,
|
||||
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
|
||||
league: {
|
||||
getEntriesByPuuid: league,
|
||||
} as Partial<RiotLeagueService>,
|
||||
mastery: {
|
||||
getTopByPuuid: mastery,
|
||||
} as Partial<RiotChampionMasteryService>,
|
||||
});
|
||||
|
||||
const result = await service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
options: { force: true, platform: 'kr' },
|
||||
});
|
||||
|
||||
expect(result.summoner).toBe('updated');
|
||||
expect(region).toHaveBeenCalledWith('puuid-1', { region: 'asia' });
|
||||
expect(summoner).toHaveBeenNthCalledWith(1, 'puuid-1', {
|
||||
platform: 'kr',
|
||||
});
|
||||
expect(summoner).toHaveBeenNthCalledWith(2, 'puuid-1', {
|
||||
platform: 'jp1',
|
||||
});
|
||||
expect(league).toHaveBeenCalledWith('puuid-1', { platform: 'jp1' });
|
||||
expect(mastery).toHaveBeenCalledWith('puuid-1', {
|
||||
platform: 'jp1',
|
||||
count: 10,
|
||||
});
|
||||
});
|
||||
|
||||
it('deduplicates concurrent enrichment for the same user and puuid', async () => {
|
||||
const account = makeAccount();
|
||||
const user = makeUser(account);
|
||||
let resolveSummoner: (value: unknown) => void;
|
||||
const summonerPromise = new Promise((resolve) => {
|
||||
resolveSummoner = resolve;
|
||||
});
|
||||
const summoner = jest.fn().mockReturnValue(summonerPromise);
|
||||
const { service } = makeService({
|
||||
user,
|
||||
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
|
||||
league: {
|
||||
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<RiotLeagueService>,
|
||||
mastery: {
|
||||
getTopByPuuid: jest.fn().mockResolvedValue([]),
|
||||
} as Partial<RiotChampionMasteryService>,
|
||||
});
|
||||
|
||||
const first = service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
options: { force: true },
|
||||
});
|
||||
const second = service.enrichRiotAccount({
|
||||
userId: user._id,
|
||||
puuid: 'puuid-1',
|
||||
options: { force: true },
|
||||
});
|
||||
|
||||
resolveSummoner!({
|
||||
puuid: 'puuid-1',
|
||||
profileIconId: 100,
|
||||
revisionDate: 1776977597000,
|
||||
summonerLevel: 30,
|
||||
});
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(summoner).toHaveBeenCalledTimes(1);
|
||||
expect(user.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,450 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
ChampionMasteryEntry,
|
||||
RiotAccount,
|
||||
TierInfo,
|
||||
} from '../global/database/schema';
|
||||
import { RiotAccountService } from './riot-account.service';
|
||||
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
|
||||
import { RiotApiError } from './riot.client.service';
|
||||
import { RiotLeagueService } from './riot-league.service';
|
||||
import {
|
||||
RIOT_RECENT_MATCH_LIMIT,
|
||||
RiotRecentMatchesService,
|
||||
} from './riot-recent-matches.service';
|
||||
import { RiotRecentStatsService } from './riot-recent-stats.service';
|
||||
import { RiotSummonerService } from './riot-summoner.service';
|
||||
import {
|
||||
RiotChampionMasteryDto,
|
||||
RiotLeagueEntryDto,
|
||||
RiotMatchDto,
|
||||
RiotPlatformRoute,
|
||||
RiotRegionalRoute,
|
||||
RiotSummonerDto,
|
||||
} from './riot.types';
|
||||
|
||||
const DEFAULT_PLATFORM: RiotPlatformRoute = 'kr';
|
||||
const DEFAULT_REGION: RiotRegionalRoute = 'asia';
|
||||
const MASTERY_LIMIT = 10;
|
||||
|
||||
const DEFAULT_SUMMONER_TTL_MS = 24 * 60 * 60 * 1000; // 24h
|
||||
const DEFAULT_LEAGUE_TTL_MS = 60 * 60 * 1000; // 1h
|
||||
const DEFAULT_MASTERY_TTL_MS = 6 * 60 * 60 * 1000; // 6h
|
||||
const DEFAULT_RECENT_MATCHES_TTL_MS = 6 * 60 * 60 * 1000; // 6h
|
||||
|
||||
export interface EnrichOptions {
|
||||
platform?: RiotPlatformRoute;
|
||||
region?: RiotRegionalRoute;
|
||||
force?: boolean;
|
||||
summonerTtlMs?: number;
|
||||
leagueTtlMs?: number;
|
||||
masteryTtlMs?: number;
|
||||
recentMatchesTtlMs?: number;
|
||||
}
|
||||
|
||||
export interface EnrichResult {
|
||||
summoner: 'updated' | 'fresh' | 'failed';
|
||||
league: 'updated' | 'fresh' | 'failed';
|
||||
masteries: 'updated' | 'fresh' | 'failed';
|
||||
recentMatches: 'updated' | 'fresh' | 'failed';
|
||||
account: RiotAccount | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RiotAccountEnrichmentService {
|
||||
private readonly logger = new Logger(RiotAccountEnrichmentService.name);
|
||||
private readonly inFlight = new Map<string, Promise<EnrichResult>>();
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly accountService: RiotAccountService,
|
||||
private readonly summonerService: RiotSummonerService,
|
||||
private readonly leagueService: RiotLeagueService,
|
||||
private readonly masteryService: RiotChampionMasteryService,
|
||||
private readonly recentMatchesService: RiotRecentMatchesService,
|
||||
private readonly recentStatsService: RiotRecentStatsService,
|
||||
) {}
|
||||
|
||||
public async markRefreshRequested(
|
||||
userId: mongoose.Types.ObjectId,
|
||||
puuid: string,
|
||||
at: Date = new Date(),
|
||||
): Promise<void> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
await UserModel.updateOne(
|
||||
{ _id: userId, 'riotAccounts.puuid': puuid },
|
||||
{ $set: { 'riotAccounts.$.lastRefreshRequestedAt': at } },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async enrichRiotAccount(params: {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
options?: EnrichOptions;
|
||||
}): Promise<EnrichResult> {
|
||||
const key = `${params.userId.toString()}:${params.puuid}`;
|
||||
const existing = this.inFlight.get(key);
|
||||
if (existing) return existing;
|
||||
|
||||
const promise = this.doEnrichRiotAccount(params).finally(() => {
|
||||
this.inFlight.delete(key);
|
||||
});
|
||||
this.inFlight.set(key, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
private async doEnrichRiotAccount(params: {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
options?: EnrichOptions;
|
||||
}): Promise<EnrichResult> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const user = await UserModel.findById(params.userId).exec();
|
||||
if (!user) {
|
||||
return {
|
||||
summoner: 'failed',
|
||||
league: 'failed',
|
||||
masteries: 'failed',
|
||||
recentMatches: 'failed',
|
||||
account: null,
|
||||
};
|
||||
}
|
||||
const account = user.riotAccounts.find((a) => a.puuid === params.puuid);
|
||||
if (!account) {
|
||||
return {
|
||||
summoner: 'failed',
|
||||
league: 'failed',
|
||||
masteries: 'failed',
|
||||
recentMatches: 'failed',
|
||||
account: null,
|
||||
};
|
||||
}
|
||||
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const community = await CommunityModel.findById(user.communityId)
|
||||
.select({ riotPlatform: 1, riotRegion: 1, seasonStartedAt: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
const opts = params.options ?? {};
|
||||
const platform =
|
||||
opts.platform ?? community?.riotPlatform ?? DEFAULT_PLATFORM;
|
||||
const region = opts.region ?? community?.riotRegion ?? DEFAULT_REGION;
|
||||
const now = Date.now();
|
||||
|
||||
const summonerTtl = opts.summonerTtlMs ?? DEFAULT_SUMMONER_TTL_MS;
|
||||
const leagueTtl = opts.leagueTtlMs ?? DEFAULT_LEAGUE_TTL_MS;
|
||||
const masteryTtl = opts.masteryTtlMs ?? DEFAULT_MASTERY_TTL_MS;
|
||||
const recentMatchesTtl =
|
||||
opts.recentMatchesTtlMs ?? DEFAULT_RECENT_MATCHES_TTL_MS;
|
||||
const force = opts.force === true;
|
||||
const seasonStartedAt = community?.seasonStartedAt
|
||||
? new Date(community.seasonStartedAt)
|
||||
: undefined;
|
||||
const seasonInvalidatesRecentStats =
|
||||
seasonStartedAt !== undefined &&
|
||||
(!account.recentStatsFetchedAt ||
|
||||
account.recentStatsFetchedAt.getTime() < seasonStartedAt.getTime());
|
||||
|
||||
const summonerStale =
|
||||
force ||
|
||||
account.revisionDate === 0 ||
|
||||
now - account.revisionDate > summonerTtl;
|
||||
const leagueStale =
|
||||
force ||
|
||||
account.tiers.length === 0 ||
|
||||
this.tiersOldestAt(account.tiers) < now - leagueTtl;
|
||||
const masteryStale =
|
||||
force ||
|
||||
!account.championMasteriesFetchedAt ||
|
||||
now - account.championMasteriesFetchedAt.getTime() > masteryTtl;
|
||||
const recentMatchesStale =
|
||||
force ||
|
||||
seasonInvalidatesRecentStats ||
|
||||
!account.recentStatsFetchedAt ||
|
||||
!account.recentStatsSummary ||
|
||||
now - account.recentStatsFetchedAt.getTime() > recentMatchesTtl;
|
||||
|
||||
const summonerOutcome = summonerStale
|
||||
? await this.fetchSummonerSafe(params.puuid, platform, region)
|
||||
: { status: 'fresh' as const, dto: null, platform };
|
||||
const effectivePlatform = summonerOutcome.platform ?? platform;
|
||||
|
||||
const [leagueOutcome, masteryOutcome, recentMatchesOutcome] =
|
||||
await Promise.all([
|
||||
leagueStale
|
||||
? this.fetchLeagueSafe(params.puuid, effectivePlatform)
|
||||
: Promise.resolve({ status: 'fresh' as const, dto: null }),
|
||||
masteryStale
|
||||
? this.fetchMasteriesSafe(params.puuid, effectivePlatform)
|
||||
: Promise.resolve({ status: 'fresh' as const, dto: null }),
|
||||
recentMatchesStale
|
||||
? this.fetchRecentMatchesSafe(params.puuid, region, seasonStartedAt)
|
||||
: Promise.resolve({
|
||||
status: 'fresh' as const,
|
||||
summary: null,
|
||||
matchIds: null,
|
||||
}),
|
||||
]);
|
||||
|
||||
if (summonerOutcome.status === 'updated' && summonerOutcome.dto) {
|
||||
this.applySummoner(account, summonerOutcome.dto);
|
||||
}
|
||||
if (leagueOutcome.status === 'updated' && leagueOutcome.dto) {
|
||||
this.applyLeagueEntries(account, leagueOutcome.dto);
|
||||
}
|
||||
if (masteryOutcome.status === 'updated' && masteryOutcome.dto) {
|
||||
this.applyMasteries(account, masteryOutcome.dto);
|
||||
}
|
||||
if (
|
||||
recentMatchesOutcome.status === 'updated' &&
|
||||
recentMatchesOutcome.summary &&
|
||||
recentMatchesOutcome.matchIds
|
||||
) {
|
||||
this.applyRecentMatches(
|
||||
account,
|
||||
recentMatchesOutcome.summary,
|
||||
recentMatchesOutcome.matchIds,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
summonerOutcome.status === 'updated' ||
|
||||
leagueOutcome.status === 'updated' ||
|
||||
masteryOutcome.status === 'updated' ||
|
||||
recentMatchesOutcome.status === 'updated'
|
||||
) {
|
||||
await user.save();
|
||||
}
|
||||
|
||||
return {
|
||||
summoner: summonerOutcome.status,
|
||||
league: leagueOutcome.status,
|
||||
masteries: masteryOutcome.status,
|
||||
recentMatches: recentMatchesOutcome.status,
|
||||
account,
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchSummonerSafe(
|
||||
puuid: string,
|
||||
platform: RiotPlatformRoute,
|
||||
region: RiotRegionalRoute,
|
||||
): Promise<
|
||||
| { status: 'updated'; dto: RiotSummonerDto; platform: RiotPlatformRoute }
|
||||
| { status: 'failed'; dto: null; platform: RiotPlatformRoute }
|
||||
> {
|
||||
try {
|
||||
const dto = await this.summonerService.getByPuuid(puuid, { platform });
|
||||
return { status: 'updated', dto, platform };
|
||||
} catch (err) {
|
||||
if (err instanceof RiotApiError && err.status === 404) {
|
||||
try {
|
||||
const regionDto = await this.accountService.getRegionByPuuid(puuid, {
|
||||
region,
|
||||
});
|
||||
if (regionDto.region !== platform) {
|
||||
this.logger.warn(
|
||||
`Summoner platform corrected for ${puuid}: ${platform} -> ${regionDto.region}`,
|
||||
);
|
||||
}
|
||||
const dto = await this.summonerService.getByPuuid(puuid, {
|
||||
platform: regionDto.region,
|
||||
});
|
||||
return { status: 'updated', dto, platform: regionDto.region };
|
||||
} catch (fallbackErr) {
|
||||
this.logger.warn(
|
||||
`Summoner fallback fetch failed for ${puuid}: ${
|
||||
(fallbackErr as Error)?.message ?? fallbackErr
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', dto: null, platform };
|
||||
}
|
||||
}
|
||||
this.logger.warn(
|
||||
`Summoner fetch failed for ${puuid}: ${(err as Error)?.message ?? err}`,
|
||||
);
|
||||
return { status: 'failed', dto: null, platform };
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchLeagueSafe(
|
||||
puuid: string,
|
||||
platform: RiotPlatformRoute,
|
||||
): Promise<
|
||||
| { status: 'updated'; dto: RiotLeagueEntryDto[] }
|
||||
| { status: 'failed'; dto: null }
|
||||
> {
|
||||
try {
|
||||
const dto = await this.leagueService.getEntriesByPuuid(puuid, {
|
||||
platform,
|
||||
});
|
||||
return { status: 'updated', dto };
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`League entries fetch failed for ${puuid}: ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', dto: null };
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchMasteriesSafe(
|
||||
puuid: string,
|
||||
platform: RiotPlatformRoute,
|
||||
): Promise<
|
||||
| { status: 'updated'; dto: RiotChampionMasteryDto[] }
|
||||
| { status: 'failed'; dto: null }
|
||||
> {
|
||||
try {
|
||||
const dto = await this.masteryService.getTopByPuuid(puuid, {
|
||||
platform,
|
||||
count: MASTERY_LIMIT,
|
||||
});
|
||||
return { status: 'updated', dto };
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Champion masteries fetch failed for ${puuid}: ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', dto: null };
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchRecentMatchesSafe(
|
||||
puuid: string,
|
||||
region: RiotRegionalRoute,
|
||||
seasonStartedAt?: Date,
|
||||
): Promise<
|
||||
| {
|
||||
status: 'updated';
|
||||
summary: RiotAccount['recentStatsSummary'];
|
||||
matchIds: string[];
|
||||
}
|
||||
| { status: 'failed'; summary: null; matchIds: null }
|
||||
> {
|
||||
try {
|
||||
await this.recentMatchesService.syncRecentMatches({
|
||||
puuid,
|
||||
region,
|
||||
limit: RIOT_RECENT_MATCH_LIMIT,
|
||||
});
|
||||
const matches = await this.recentMatchesService.loadFromDb({
|
||||
puuid,
|
||||
limit: RIOT_RECENT_MATCH_LIMIT,
|
||||
});
|
||||
const summary = this.recentStatsService.computeSummary(
|
||||
matches.map((match) => match.raw as unknown as RiotMatchDto),
|
||||
puuid,
|
||||
{ seasonStartedAt },
|
||||
);
|
||||
return {
|
||||
status: 'updated',
|
||||
summary,
|
||||
matchIds: matches.map((match) => match.matchId),
|
||||
};
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Recent matches fetch failed for ${puuid}: ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', summary: null, matchIds: null };
|
||||
}
|
||||
}
|
||||
|
||||
private applySummoner(account: RiotAccount, dto: RiotSummonerDto): void {
|
||||
account.profileIconId = dto.profileIconId;
|
||||
account.revisionDate = dto.revisionDate;
|
||||
account.summonerLevel = dto.summonerLevel;
|
||||
}
|
||||
|
||||
private applyLeagueEntries(
|
||||
account: RiotAccount,
|
||||
entries: RiotLeagueEntryDto[],
|
||||
): void {
|
||||
const fetchedAt = new Date();
|
||||
this.appendTierHistoryIfChanged(account, entries, fetchedAt);
|
||||
const next: TierInfo[] = entries.map((e) => ({
|
||||
leagueId: e.leagueId,
|
||||
queueType: e.queueType,
|
||||
tier: e.tier,
|
||||
rank: e.rank,
|
||||
puuid: e.puuid,
|
||||
leaguePoints: e.leaguePoints,
|
||||
wins: e.wins,
|
||||
losses: e.losses,
|
||||
veteran: e.veteran,
|
||||
inactive: e.inactive,
|
||||
freshBlood: e.freshBlood,
|
||||
hotStreak: e.hotStreak,
|
||||
miniSeries: e.miniSeries,
|
||||
fetchedAt,
|
||||
}));
|
||||
account.tiers = next;
|
||||
}
|
||||
|
||||
private appendTierHistoryIfChanged(
|
||||
account: RiotAccount,
|
||||
entries: RiotLeagueEntryDto[],
|
||||
recordedAt: Date,
|
||||
): void {
|
||||
for (const entry of entries) {
|
||||
const last = [...account.tierHistory]
|
||||
.reverse()
|
||||
.find((history) => history.queueType === entry.queueType);
|
||||
const changed =
|
||||
!last ||
|
||||
last.tier !== entry.tier ||
|
||||
(last.rank ?? '') !== (entry.rank ?? '');
|
||||
if (!changed) continue;
|
||||
|
||||
account.tierHistory.push({
|
||||
queueType: entry.queueType,
|
||||
tier: entry.tier,
|
||||
rank: entry.rank,
|
||||
leaguePoints: entry.leaguePoints,
|
||||
wins: entry.wins,
|
||||
losses: entry.losses,
|
||||
recordedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private applyMasteries(
|
||||
account: RiotAccount,
|
||||
masteries: RiotChampionMasteryDto[],
|
||||
): void {
|
||||
const summary: ChampionMasteryEntry[] = masteries
|
||||
.slice(0, MASTERY_LIMIT)
|
||||
.map((m) => ({ ...m }));
|
||||
account.championMasteries = summary;
|
||||
account.championMasteriesFetchedAt = new Date();
|
||||
}
|
||||
|
||||
private applyRecentMatches(
|
||||
account: RiotAccount,
|
||||
summary: NonNullable<RiotAccount['recentStatsSummary']>,
|
||||
matchIds: string[],
|
||||
): void {
|
||||
const fetchedAt = new Date();
|
||||
account.recentStatsSummary = summary;
|
||||
account.recentStatsFetchedAt = fetchedAt;
|
||||
account.matchIds = matchIds;
|
||||
account.matchIdsFetchedAt = fetchedAt;
|
||||
}
|
||||
|
||||
private tiersOldestAt(tiers: TierInfo[]): number {
|
||||
if (tiers.length === 0) return 0;
|
||||
let oldest = Infinity;
|
||||
for (const t of tiers) {
|
||||
const at = t.fetchedAt instanceof Date ? t.fetchedAt.getTime() : 0;
|
||||
if (at < oldest) oldest = at;
|
||||
}
|
||||
return oldest === Infinity ? 0 : oldest;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { SecretModule } from '../global/secret/secret.module';
|
||||
import { RiotAccountEnrichmentService } from './riot-account-enrichment.service';
|
||||
import { RiotAccountService } from './riot-account.service';
|
||||
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
|
||||
import { RiotClientService } from './riot.client.service';
|
||||
import { RiotDdragonController } from './riot-ddragon.controller';
|
||||
import { RiotDdragonService } from './riot-ddragon.service';
|
||||
import { RiotLeagueService } from './riot-league.service';
|
||||
import { RiotMatchService } from './riot-match.service';
|
||||
import { RiotRateLimiterService } from './riot-rate-limiter.service';
|
||||
import { RiotRecentMatchesService } from './riot-recent-matches.service';
|
||||
import { RiotRecentStatsService } from './riot-recent-stats.service';
|
||||
import { RiotSummonerService } from './riot-summoner.service';
|
||||
import { RiotWebhookController } from './riot-webhook.controller';
|
||||
|
||||
@Module({
|
||||
imports: [SecretModule],
|
||||
controllers: [RiotWebhookController, RiotDdragonController],
|
||||
providers: [
|
||||
RiotRateLimiterService,
|
||||
RiotClientService,
|
||||
RiotAccountService,
|
||||
RiotMatchService,
|
||||
RiotRecentMatchesService,
|
||||
RiotRecentStatsService,
|
||||
RiotSummonerService,
|
||||
RiotLeagueService,
|
||||
RiotChampionMasteryService,
|
||||
RiotAccountEnrichmentService,
|
||||
RiotDdragonService,
|
||||
],
|
||||
exports: [
|
||||
RiotRateLimiterService,
|
||||
RiotClientService,
|
||||
RiotAccountService,
|
||||
RiotMatchService,
|
||||
RiotRecentMatchesService,
|
||||
RiotRecentStatsService,
|
||||
RiotSummonerService,
|
||||
RiotLeagueService,
|
||||
RiotChampionMasteryService,
|
||||
RiotAccountEnrichmentService,
|
||||
RiotDdragonService,
|
||||
],
|
||||
})
|
||||
export class RiotModule {}
|
||||
Reference in new issue
Block a user