986 lines
27 KiB
TypeScript
986 lines
27 KiB
TypeScript
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';
|
|
import { type RiotPlatformRoute, type RiotRegionalRoute } from './riot.types';
|
|
|
|
interface FakeAccount {
|
|
puuid: string;
|
|
gameName: string;
|
|
tagLine: 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',
|
|
gameName: 'OldName',
|
|
tagLine: 'KR1',
|
|
profileIconId: 0,
|
|
revisionDate: 0,
|
|
summonerLevel: 0,
|
|
matchIds: [],
|
|
tiers: [],
|
|
tierHistory: [],
|
|
championMasteries: [],
|
|
championRecords: {},
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function makeUser(account: FakeAccount) {
|
|
const _id = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const save = jest.fn().mockResolvedValue(undefined);
|
|
return {
|
|
_id,
|
|
communityId,
|
|
riotAccounts: [account],
|
|
save,
|
|
};
|
|
}
|
|
|
|
function makeService(overrides?: {
|
|
user?: any;
|
|
community?: {
|
|
riotPlatform?: RiotPlatformRoute;
|
|
riotRegion?: RiotRegionalRoute;
|
|
seasonStartedAt?: Date;
|
|
};
|
|
account?: Partial<RiotAccountService>;
|
|
summoner?: Partial<RiotSummonerService>;
|
|
league?: Partial<RiotLeagueService>;
|
|
mastery?: Partial<RiotChampionMasteryService>;
|
|
recentMatches?: Partial<RiotRecentMatchesService>;
|
|
recentStats?: Partial<RiotRecentStatsService>;
|
|
match?: any;
|
|
}) {
|
|
const user = overrides?.user;
|
|
const userFindById = jest.fn().mockReturnValue({
|
|
exec: () => Promise.resolve(user ?? null),
|
|
});
|
|
const communityFindById = jest.fn().mockReturnValue({
|
|
select: () => ({
|
|
lean: () => ({
|
|
exec: () =>
|
|
Promise.resolve(
|
|
overrides?.community ?? {
|
|
riotPlatform: 'kr',
|
|
riotRegion: 'asia',
|
|
},
|
|
),
|
|
}),
|
|
}),
|
|
});
|
|
const matchUpdateManyExec = jest.fn().mockResolvedValue({ modifiedCount: 0 });
|
|
const matchModel = {
|
|
updateMany: jest.fn().mockReturnValue({ exec: matchUpdateManyExec }),
|
|
...overrides?.match,
|
|
};
|
|
const connectionService = {
|
|
getModel: jest.fn().mockImplementation(async (modelName: string) => {
|
|
if (modelName === 'user') {
|
|
return { findById: userFindById };
|
|
}
|
|
if (modelName === 'community') {
|
|
return { findById: communityFindById };
|
|
}
|
|
if (modelName === 'match') {
|
|
return matchModel;
|
|
}
|
|
throw new Error(`Unexpected model: ${modelName}`);
|
|
}),
|
|
} as unknown as ConnectionService;
|
|
|
|
const summonerService = {
|
|
getByPuuid: jest.fn(),
|
|
...overrides?.summoner,
|
|
} as unknown as RiotSummonerService;
|
|
const accountService = {
|
|
getByPuuid: jest.fn(),
|
|
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,
|
|
matchModel,
|
|
matchUpdateManyExec,
|
|
};
|
|
}
|
|
|
|
describe('RiotAccountEnrichmentService', () => {
|
|
it('updates a changed Riot ID resolved from the stored PUUID', async () => {
|
|
const account = makeAccount();
|
|
const user = makeUser(account);
|
|
const { service, accountService } = makeService({
|
|
user,
|
|
account: {
|
|
getByPuuid: jest.fn().mockResolvedValue({
|
|
puuid: 'puuid-1',
|
|
gameName: 'NewName',
|
|
tagLine: 'KR1',
|
|
}),
|
|
},
|
|
});
|
|
|
|
const result = await service.refreshRiotIdentity({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
region: 'europe',
|
|
});
|
|
|
|
expect(result).toBe('updated');
|
|
expect(account.gameName).toBe('NewName');
|
|
expect(account.tagLine).toBe('KR1');
|
|
expect(user.save).toHaveBeenCalledTimes(1);
|
|
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
|
|
region: 'europe',
|
|
});
|
|
});
|
|
|
|
it('updates a changed Riot tag line resolved from the stored PUUID', async () => {
|
|
const account = makeAccount();
|
|
const user = makeUser(account);
|
|
const { service } = makeService({
|
|
user,
|
|
account: {
|
|
getByPuuid: jest.fn().mockResolvedValue({
|
|
puuid: 'puuid-1',
|
|
gameName: 'OldName',
|
|
tagLine: 'NEW',
|
|
}),
|
|
},
|
|
});
|
|
|
|
const result = await service.refreshRiotIdentity({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
});
|
|
|
|
expect(result).toBe('updated');
|
|
expect(account.gameName).toBe('OldName');
|
|
expect(account.tagLine).toBe('NEW');
|
|
expect(user.save).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('resolves the Riot region from the user community when none is provided', async () => {
|
|
const account = makeAccount();
|
|
const user = makeUser(account);
|
|
const { service, accountService } = makeService({
|
|
user,
|
|
community: {
|
|
riotPlatform: 'na1',
|
|
riotRegion: 'americas',
|
|
},
|
|
account: {
|
|
getByPuuid: jest.fn().mockResolvedValue({
|
|
puuid: 'puuid-1',
|
|
gameName: 'NewName',
|
|
tagLine: 'NA1',
|
|
}),
|
|
},
|
|
});
|
|
|
|
await service.refreshRiotIdentity({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
});
|
|
|
|
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
|
|
region: 'americas',
|
|
});
|
|
});
|
|
|
|
it('falls back to the default Riot region when the community has no region', async () => {
|
|
const account = makeAccount();
|
|
const user = makeUser(account);
|
|
const { service, accountService } = makeService({
|
|
user,
|
|
community: {
|
|
riotPlatform: 'kr',
|
|
},
|
|
account: {
|
|
getByPuuid: jest.fn().mockResolvedValue({
|
|
puuid: 'puuid-1',
|
|
gameName: 'NewName',
|
|
tagLine: 'KR1',
|
|
}),
|
|
},
|
|
});
|
|
|
|
await service.refreshRiotIdentity({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
});
|
|
|
|
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
|
|
region: 'asia',
|
|
});
|
|
});
|
|
|
|
it('does not save when the Riot ID has not changed', async () => {
|
|
const account = makeAccount();
|
|
const user = makeUser(account);
|
|
const { service } = makeService({
|
|
user,
|
|
account: {
|
|
getByPuuid: jest.fn().mockResolvedValue({
|
|
puuid: 'puuid-1',
|
|
gameName: 'OldName',
|
|
tagLine: 'KR1',
|
|
}),
|
|
},
|
|
});
|
|
|
|
const result = await service.refreshRiotIdentity({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
});
|
|
|
|
expect(result).toBe('unchanged');
|
|
expect(user.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([
|
|
{
|
|
name: 'a mismatched PUUID',
|
|
response: {
|
|
puuid: 'different-puuid',
|
|
gameName: 'NewName',
|
|
tagLine: 'NEW',
|
|
},
|
|
},
|
|
{
|
|
name: 'a missing game name',
|
|
response: {
|
|
puuid: 'puuid-1',
|
|
gameName: null,
|
|
tagLine: 'NEW',
|
|
},
|
|
},
|
|
{
|
|
name: 'a blank tag line',
|
|
response: {
|
|
puuid: 'puuid-1',
|
|
gameName: 'NewName',
|
|
tagLine: ' ',
|
|
},
|
|
},
|
|
])('preserves the stored Riot ID for $name', async ({ response }) => {
|
|
const account = makeAccount();
|
|
const user = makeUser(account);
|
|
const { service } = makeService({
|
|
user,
|
|
account: {
|
|
getByPuuid: jest.fn().mockResolvedValue(response),
|
|
},
|
|
});
|
|
|
|
const result = await service.refreshRiotIdentity({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
});
|
|
|
|
expect(result).toBe('failed');
|
|
expect(account.gameName).toBe('OldName');
|
|
expect(account.tagLine).toBe('KR1');
|
|
expect(user.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('preserves the stored Riot ID when Account-V1 lookup fails', async () => {
|
|
const account = makeAccount();
|
|
const user = makeUser(account);
|
|
const { service } = makeService({
|
|
user,
|
|
account: {
|
|
getByPuuid: jest.fn().mockRejectedValue(new Error('Riot unavailable')),
|
|
},
|
|
});
|
|
|
|
const result = await service.refreshRiotIdentity({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
});
|
|
|
|
expect(result).toBe('failed');
|
|
expect(account.gameName).toBe('OldName');
|
|
expect(account.tagLine).toBe('KR1');
|
|
expect(user.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
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('refreshes league entries without refreshing recent matches', async () => {
|
|
const recent = new Date(Date.now() - 60_000);
|
|
const account = makeAccount({
|
|
revisionDate: Date.now() - 60_000,
|
|
tiers: [
|
|
{
|
|
leagueId: 'L1',
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'GOLD',
|
|
rank: 'II',
|
|
puuid: 'puuid-1',
|
|
leaguePoints: 1,
|
|
wins: 1,
|
|
losses: 1,
|
|
fetchedAt: recent,
|
|
},
|
|
],
|
|
recentStatsFetchedAt: recent,
|
|
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
|
|
});
|
|
const user = makeUser(account);
|
|
const { service, leagueService, recentMatchesService } = makeService({
|
|
user,
|
|
league: {
|
|
getEntriesByPuuid: jest.fn().mockResolvedValue([
|
|
{
|
|
leagueId: 'L2',
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'PLATINUM',
|
|
rank: 'IV',
|
|
puuid: 'puuid-1',
|
|
leaguePoints: 20,
|
|
wins: 10,
|
|
losses: 8,
|
|
},
|
|
]),
|
|
} as Partial<RiotLeagueService>,
|
|
});
|
|
|
|
const result = await service.refreshLeagueEntries({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
platform: 'kr',
|
|
});
|
|
|
|
expect(result).toBe('updated');
|
|
expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', {
|
|
platform: 'kr',
|
|
});
|
|
expect(recentMatchesService.syncRecentMatches).not.toHaveBeenCalled();
|
|
expect(account.tiers).toHaveLength(1);
|
|
expect(account.tiers[0]).toMatchObject({
|
|
leagueId: 'L2',
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'PLATINUM',
|
|
rank: 'IV',
|
|
leaguePoints: 20,
|
|
});
|
|
expect(account.tierHistory.at(-1)).toMatchObject({
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'PLATINUM',
|
|
rank: 'IV',
|
|
leaguePoints: 20,
|
|
});
|
|
expect(user.save).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('appends tier history when LP changes without tier or rank changes', async () => {
|
|
const recent = new Date(Date.now() - 60_000);
|
|
const account = makeAccount({
|
|
revisionDate: Date.now() - 60_000,
|
|
tiers: [
|
|
{
|
|
leagueId: 'L1',
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'GOLD',
|
|
rank: 'II',
|
|
puuid: 'puuid-1',
|
|
leaguePoints: 10,
|
|
wins: 20,
|
|
losses: 12,
|
|
fetchedAt: recent,
|
|
},
|
|
],
|
|
tierHistory: [
|
|
{
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'GOLD',
|
|
rank: 'II',
|
|
leaguePoints: 10,
|
|
wins: 20,
|
|
losses: 12,
|
|
recordedAt: recent,
|
|
},
|
|
],
|
|
recentStatsFetchedAt: recent,
|
|
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
|
|
});
|
|
const user = makeUser(account);
|
|
const { service } = makeService({
|
|
user,
|
|
league: {
|
|
getEntriesByPuuid: jest.fn().mockResolvedValue([
|
|
{
|
|
leagueId: 'L1',
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'GOLD',
|
|
rank: 'II',
|
|
puuid: 'puuid-1',
|
|
leaguePoints: 44,
|
|
wins: 21,
|
|
losses: 12,
|
|
},
|
|
]),
|
|
} as Partial<RiotLeagueService>,
|
|
});
|
|
|
|
await service.refreshLeagueEntries({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
platform: 'kr',
|
|
});
|
|
|
|
expect(account.tierHistory).toHaveLength(2);
|
|
expect(account.tierHistory.at(-1)).toMatchObject({
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'GOLD',
|
|
rank: 'II',
|
|
leaguePoints: 44,
|
|
wins: 21,
|
|
losses: 12,
|
|
});
|
|
});
|
|
|
|
it('syncs refreshed league tier into active match participant snapshots', async () => {
|
|
const recent = new Date(Date.now() - 60_000);
|
|
const account = makeAccount({
|
|
revisionDate: Date.now() - 60_000,
|
|
tiers: [
|
|
{
|
|
leagueId: 'L1',
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'GOLD',
|
|
rank: 'II',
|
|
puuid: 'puuid-1',
|
|
leaguePoints: 1,
|
|
wins: 1,
|
|
losses: 1,
|
|
fetchedAt: recent,
|
|
},
|
|
],
|
|
recentStatsFetchedAt: recent,
|
|
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
|
|
});
|
|
const user = makeUser(account);
|
|
const { service, matchModel } = makeService({
|
|
user,
|
|
league: {
|
|
getEntriesByPuuid: jest.fn().mockResolvedValue([
|
|
{
|
|
leagueId: 'L2',
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'PLATINUM',
|
|
rank: 'IV',
|
|
puuid: 'puuid-1',
|
|
leaguePoints: 20,
|
|
wins: 10,
|
|
losses: 8,
|
|
},
|
|
]),
|
|
} as Partial<RiotLeagueService>,
|
|
});
|
|
|
|
await service.refreshLeagueEntries({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
platform: 'kr',
|
|
});
|
|
|
|
expect(matchModel.updateMany).toHaveBeenCalledWith(
|
|
{
|
|
status: { $in: ['recruiting', 'team-built', 'in-progress'] },
|
|
participants: {
|
|
$elemMatch: {
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
},
|
|
},
|
|
},
|
|
{
|
|
$set: {
|
|
'participants.$[participant].tier': expect.objectContaining({
|
|
leagueId: 'L2',
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'PLATINUM',
|
|
rank: 'IV',
|
|
leaguePoints: 20,
|
|
}),
|
|
},
|
|
},
|
|
{
|
|
arrayFilters: [
|
|
{
|
|
'participant.userId': user._id,
|
|
'participant.puuid': 'puuid-1',
|
|
},
|
|
],
|
|
},
|
|
);
|
|
});
|
|
|
|
it('clears active match participant tier when refreshed league entries are empty', async () => {
|
|
const recent = new Date(Date.now() - 60_000);
|
|
const account = makeAccount({
|
|
revisionDate: Date.now() - 60_000,
|
|
tiers: [
|
|
{
|
|
leagueId: 'L1',
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'GOLD',
|
|
rank: 'II',
|
|
puuid: 'puuid-1',
|
|
leaguePoints: 1,
|
|
wins: 1,
|
|
losses: 1,
|
|
fetchedAt: recent,
|
|
},
|
|
],
|
|
recentStatsFetchedAt: recent,
|
|
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
|
|
});
|
|
const user = makeUser(account);
|
|
const { service, matchModel } = makeService({
|
|
user,
|
|
league: {
|
|
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
|
|
} as Partial<RiotLeagueService>,
|
|
});
|
|
|
|
await service.refreshLeagueEntries({
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
platform: 'kr',
|
|
});
|
|
|
|
expect(matchModel.updateMany).toHaveBeenCalledWith(
|
|
{
|
|
status: { $in: ['recruiting', 'team-built', 'in-progress'] },
|
|
participants: {
|
|
$elemMatch: {
|
|
userId: user._id,
|
|
puuid: 'puuid-1',
|
|
},
|
|
},
|
|
},
|
|
{ $unset: { 'participants.$[participant].tier': '' } },
|
|
{
|
|
arrayFilters: [
|
|
{
|
|
'participant.userId': user._id,
|
|
'participant.puuid': 'puuid-1',
|
|
},
|
|
],
|
|
},
|
|
);
|
|
});
|
|
|
|
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);
|
|
});
|
|
});
|