This commit is contained in:
dahyeon committed 2026-04-25 11:49:21 -07:00
1 parent 5af2c80cd1
commit f7ee34da4f
78 files changed
+9016 -150

No files matched your search

@@ -0,0 +1,391 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
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 { RiotSummonerService } from './riot-summoner.service';
interface FakeAccount {
puuid: string;
profileIconId: number;
revisionDate: number;
summonerLevel: number;
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,
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>;
}) {
const user = overrides?.user;
const findById = jest.fn().mockReturnValue({
exec: () => Promise.resolve(user ?? null),
});
const connectionService = {
getModel: jest.fn().mockResolvedValue({ findById }),
} 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 service = new RiotAccountEnrichmentService(
connectionService,
accountService,
summonerService,
leagueService,
masteryService,
);
return {
service,
user,
accountService,
summonerService,
leagueService,
masteryService,
};
}
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.account).toBeNull();
});
it('fills summoner / league / mastery on first attach (force)', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service, summonerService, leagueService, masteryService } =
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>,
});
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(account.profileIconId).toBe(588);
expect(account.summonerLevel).toBe(529);
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,
});
});
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,
});
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(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(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,329 @@
import { Injectable, Logger } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
ChampionMasteryEntry,
RiotAccount,
TierInfo,
UserDocument,
} 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 { RiotSummonerService } from './riot-summoner.service';
import {
RiotChampionMasteryDto,
RiotLeagueEntryDto,
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
export interface EnrichOptions {
platform?: RiotPlatformRoute;
region?: RiotRegionalRoute;
force?: boolean;
summonerTtlMs?: number;
leagueTtlMs?: number;
masteryTtlMs?: number;
}
export interface EnrichResult {
summoner: 'updated' | 'fresh' | 'failed';
league: 'updated' | 'fresh' | 'failed';
masteries: '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,
) {}
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',
account: null,
};
}
const account = user.riotAccounts.find((a) => a.puuid === params.puuid);
if (!account) {
return {
summoner: 'failed',
league: 'failed',
masteries: 'failed',
account: null,
};
}
const opts = params.options ?? {};
const platform = opts.platform ?? DEFAULT_PLATFORM;
const region = opts.region ?? 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 force = opts.force === true;
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 summonerOutcome = summonerStale
? await this.fetchSummonerSafe(params.puuid, platform, region)
: { status: 'fresh' as const, dto: null, platform };
const effectivePlatform = summonerOutcome.platform ?? platform;
const [leagueOutcome, masteryOutcome] = 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 }),
]);
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 (
summonerOutcome.status === 'updated' ||
leagueOutcome.status === 'updated' ||
masteryOutcome.status === 'updated'
) {
await user.save();
}
return {
summoner: summonerOutcome.status,
league: leagueOutcome.status,
masteries: masteryOutcome.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 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 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;
}
}
@@ -1,8 +1,10 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RIOT_PLATFORM_ROUTES,
RiotAccountDto,
RiotAccountLookupOptions,
RiotAccountRegionDto,
} from './riot.types';
@Injectable()
@@ -37,6 +39,20 @@ export class RiotAccountService {
parseRiotAccountDto,
);
}
public async getRegionByPuuid(
puuid: string,
options: RiotAccountLookupOptions = {},
): Promise<RiotAccountRegionDto> {
return this.riotClientService.get<RiotAccountRegionDto>(
`/riot/account/v1/region/by-game/lol/by-puuid/${encodeURIComponent(puuid)}`,
{
region: options.region ?? 'asia',
signal: options.signal,
},
parseRiotAccountRegionDto,
);
}
}
function parseRiotAccountDto(value: unknown): RiotAccountDto {
@@ -67,6 +83,38 @@ function parseRiotAccountDto(value: unknown): RiotAccountDto {
};
}
function parseRiotAccountRegionDto(value: unknown): RiotAccountRegionDto {
if (!isRecord(value)) {
throw new TypeError('Riot account region response must be an object.');
}
const puuid = value.puuid;
const game = value.game;
const region = value.region;
if (!isNonEmptyString(puuid)) {
throw new TypeError(
'Riot account region response is missing a valid puuid.',
);
}
if (!isNonEmptyString(game)) {
throw new TypeError(
'Riot account region response is missing a valid game.',
);
}
const platformRegion = region as (typeof RIOT_PLATFORM_ROUTES)[number];
if (
!isNonEmptyString(region) ||
!RIOT_PLATFORM_ROUTES.includes(platformRegion)
) {
throw new TypeError(
'Riot account region response is missing a valid region.',
);
}
return { puuid, game, region: platformRegion };
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -0,0 +1,129 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotChampionMasteryDto,
RiotPlatformLookupOptions,
} from './riot.types';
interface MasteriesByPuuidOptions extends RiotPlatformLookupOptions {
count?: number;
}
const DEFAULT_TOP_MASTERY_COUNT = 10;
const MAX_TOP_MASTERY_COUNT = 10;
@Injectable()
export class RiotChampionMasteryService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getByPuuid(
puuid: string,
options: RiotPlatformLookupOptions = {},
): Promise<RiotChampionMasteryDto[]> {
return this.riotClientService.get<RiotChampionMasteryDto[]>(
`/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
},
parseMasteries,
);
}
public async getTopByPuuid(
puuid: string,
options: MasteriesByPuuidOptions = {},
): Promise<RiotChampionMasteryDto[]> {
const count = options.count ?? DEFAULT_TOP_MASTERY_COUNT;
if (
!Number.isInteger(count) ||
count <= 0 ||
count > MAX_TOP_MASTERY_COUNT
) {
throw new RangeError('count must be an integer between 1 and 10.');
}
return this.riotClientService.get<RiotChampionMasteryDto[]>(
`/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
query: { count },
},
parseMasteries,
);
}
}
function parseMasteries(value: unknown): RiotChampionMasteryDto[] {
if (!Array.isArray(value)) {
throw new TypeError('Champion masteries response must be an array.');
}
return value.map((entry, index) => parseEntry(entry, index));
}
function parseEntry(value: unknown, index: number): RiotChampionMasteryDto {
if (!isRecord(value)) {
throw new TypeError(`championMasteries[${index}] must be an object.`);
}
const puuid = value.puuid;
const championId = value.championId;
const championLevel = value.championLevel;
const championPoints = value.championPoints;
if (typeof puuid !== 'string') {
throw new TypeError(`championMasteries[${index}].puuid must be a string.`);
}
if (typeof championId !== 'number' || !Number.isFinite(championId)) {
throw new TypeError(
`championMasteries[${index}].championId must be a number.`,
);
}
if (typeof championLevel !== 'number' || !Number.isFinite(championLevel)) {
throw new TypeError(
`championMasteries[${index}].championLevel must be a number.`,
);
}
if (typeof championPoints !== 'number' || !Number.isFinite(championPoints)) {
throw new TypeError(
`championMasteries[${index}].championPoints must be a number.`,
);
}
return {
...value,
puuid,
championId,
championLevel,
championPoints,
lastPlayTime:
typeof value.lastPlayTime === 'number' ? value.lastPlayTime : undefined,
championPointsSinceLastLevel:
typeof value.championPointsSinceLastLevel === 'number'
? value.championPointsSinceLastLevel
: undefined,
championPointsUntilNextLevel:
typeof value.championPointsUntilNextLevel === 'number'
? value.championPointsUntilNextLevel
: undefined,
markRequiredForNextLevel:
typeof value.markRequiredForNextLevel === 'number'
? value.markRequiredForNextLevel
: undefined,
tokensEarned:
typeof value.tokensEarned === 'number' ? value.tokensEarned : undefined,
championSeasonMilestone:
typeof value.championSeasonMilestone === 'number'
? value.championSeasonMilestone
: undefined,
milestoneGrades: Array.isArray(value.milestoneGrades)
? (value.milestoneGrades as unknown[]).filter(
(v): v is string => typeof v === 'string',
)
: undefined,
nextSeasonMilestone: isRecord(value.nextSeasonMilestone)
? value.nextSeasonMilestone
: undefined,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -0,0 +1,79 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotLeagueEntryDto,
RiotPlatformLookupOptions,
} from './riot.types';
@Injectable()
export class RiotLeagueService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getEntriesByPuuid(
puuid: string,
options: RiotPlatformLookupOptions = {},
): Promise<RiotLeagueEntryDto[]> {
return this.riotClientService.get<RiotLeagueEntryDto[]>(
`/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
},
parseLeagueEntries,
);
}
}
function parseLeagueEntries(value: unknown): RiotLeagueEntryDto[] {
if (!Array.isArray(value)) {
throw new TypeError('League entries response must be an array.');
}
return value.map((entry, index) => parseEntry(entry, index));
}
function parseEntry(value: unknown, index: number): RiotLeagueEntryDto {
if (!isRecord(value)) {
throw new TypeError(`leagueEntries[${index}] must be an object.`);
}
return {
leagueId: requireString(value.leagueId, `leagueEntries[${index}].leagueId`),
queueType: requireString(
value.queueType,
`leagueEntries[${index}].queueType`,
),
tier: requireString(value.tier, `leagueEntries[${index}].tier`),
rank: requireString(value.rank, `leagueEntries[${index}].rank`),
puuid: requireString(value.puuid, `leagueEntries[${index}].puuid`),
leaguePoints: requireNumber(
value.leaguePoints,
`leagueEntries[${index}].leaguePoints`,
),
wins: requireNumber(value.wins, `leagueEntries[${index}].wins`),
losses: requireNumber(value.losses, `leagueEntries[${index}].losses`),
veteran: typeof value.veteran === 'boolean' ? value.veteran : undefined,
inactive: typeof value.inactive === 'boolean' ? value.inactive : undefined,
freshBlood:
typeof value.freshBlood === 'boolean' ? value.freshBlood : undefined,
hotStreak:
typeof value.hotStreak === 'boolean' ? value.hotStreak : undefined,
miniSeries: isRecord(value.miniSeries) ? value.miniSeries : undefined,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function requireString(value: unknown, path: string): string {
if (typeof value !== 'string' || value.length === 0) {
throw new TypeError(`${path} must be a non-empty string.`);
}
return value;
}
function requireNumber(value: unknown, path: string): number {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new TypeError(`${path} must be a finite number.`);
}
return value;
}
@@ -0,0 +1,60 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotPlatformLookupOptions,
RiotSummonerDto,
} from './riot.types';
@Injectable()
export class RiotSummonerService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getByPuuid(
puuid: string,
options: RiotPlatformLookupOptions = {},
): Promise<RiotSummonerDto> {
return this.riotClientService.get<RiotSummonerDto>(
`/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(puuid)}`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
},
parseSummoner,
);
}
}
function parseSummoner(value: unknown): RiotSummonerDto {
if (!isRecord(value)) {
throw new TypeError('Riot summoner response must be an object.');
}
const puuid = value.puuid;
const profileIconId = value.profileIconId;
const revisionDate = value.revisionDate;
const summonerLevel = value.summonerLevel;
if (typeof puuid !== 'string' || puuid.length === 0) {
throw new TypeError('Summoner.puuid must be a non-empty string.');
}
if (typeof profileIconId !== 'number') {
throw new TypeError('Summoner.profileIconId must be a number.');
}
if (typeof revisionDate !== 'number') {
throw new TypeError('Summoner.revisionDate must be a number.');
}
if (typeof summonerLevel !== 'number') {
throw new TypeError('Summoner.summonerLevel must be a number.');
}
return {
puuid,
profileIconId,
revisionDate,
summonerLevel,
id: typeof value.id === 'string' ? value.id : undefined,
accountId:
typeof value.accountId === 'string' ? value.accountId : undefined,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -6,6 +6,7 @@ import {
Req,
} from '@nestjs/common';
import type { Request } from 'express';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
type RiotWebhookRequest = Request & {
rawBody?: Buffer;
@@ -14,6 +15,7 @@ type RiotWebhookRequest = Request & {
@Controller('riot')
export class RiotWebhookController {
@All('webhooks/tournament')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public captureTournamentWebhook(@Req() req: RiotWebhookRequest) {
const receivedAt = new Date().toISOString();
@@ -2,18 +2,39 @@ import { Injectable, Logger } from '@nestjs/common';
import { SecretService } from '../global/secret/secret.service';
import {
RiotApiErrorBody,
RiotPlatformRoute,
RiotRegionalRoute,
RiotRequestOptions,
RiotResponseParser,
} from './riot.types';
const RIOT_BASE_URLS: Record<RiotRegionalRoute, string> = {
const RIOT_REGION_BASE_URLS: Record<RiotRegionalRoute, string> = {
americas: 'https://americas.api.riotgames.com',
asia: 'https://asia.api.riotgames.com',
europe: 'https://europe.api.riotgames.com',
sea: 'https://sea.api.riotgames.com',
};
const RIOT_PLATFORM_BASE_URLS: Record<RiotPlatformRoute, string> = {
br1: 'https://br1.api.riotgames.com',
eun1: 'https://eun1.api.riotgames.com',
euw1: 'https://euw1.api.riotgames.com',
jp1: 'https://jp1.api.riotgames.com',
kr: 'https://kr.api.riotgames.com',
la1: 'https://la1.api.riotgames.com',
la2: 'https://la2.api.riotgames.com',
me1: 'https://me1.api.riotgames.com',
na1: 'https://na1.api.riotgames.com',
oc1: 'https://oc1.api.riotgames.com',
ph2: 'https://ph2.api.riotgames.com',
ru: 'https://ru.api.riotgames.com',
sg2: 'https://sg2.api.riotgames.com',
th2: 'https://th2.api.riotgames.com',
tr1: 'https://tr1.api.riotgames.com',
tw2: 'https://tw2.api.riotgames.com',
vn2: 'https://vn2.api.riotgames.com',
};
export class RiotApiError extends Error {
constructor(
message: string,
@@ -67,8 +88,9 @@ export class RiotClientService {
}
private buildUrl(path: string, options: RiotRequestOptions): string {
const region = options.region ?? 'asia';
const baseUrl = RIOT_BASE_URLS[region];
const baseUrl = options.platform
? RIOT_PLATFORM_BASE_URLS[options.platform]
: RIOT_REGION_BASE_URLS[options.region ?? 'asia'];
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
const url = new URL(`${baseUrl}${normalizedPath}`);
+22 -2
View File
@@ -1,14 +1,34 @@
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 { RiotLeagueService } from './riot-league.service';
import { RiotMatchService } from './riot-match.service';
import { RiotSummonerService } from './riot-summoner.service';
import { RiotWebhookController } from './riot-webhook.controller';
@Module({
imports: [SecretModule],
controllers: [RiotWebhookController],
providers: [RiotClientService, RiotAccountService, RiotMatchService],
exports: [RiotClientService, RiotAccountService, RiotMatchService],
providers: [
RiotClientService,
RiotAccountService,
RiotMatchService,
RiotSummonerService,
RiotLeagueService,
RiotChampionMasteryService,
RiotAccountEnrichmentService,
],
exports: [
RiotClientService,
RiotAccountService,
RiotMatchService,
RiotSummonerService,
RiotLeagueService,
RiotChampionMasteryService,
RiotAccountEnrichmentService,
],
})
export class RiotModule {}
+83 -1
View File
@@ -1,6 +1,39 @@
export type RiotRegionalRoute = 'americas' | 'asia' | 'europe' | 'sea';
export const RIOT_REGIONAL_ROUTES = [
'americas',
'asia',
'europe',
'sea',
] as const;
export type RiotRegionalRoute = (typeof RIOT_REGIONAL_ROUTES)[number];
export const RIOT_PLATFORM_ROUTES = [
'br1',
'eun1',
'euw1',
'jp1',
'kr',
'la1',
'la2',
'me1',
'na1',
'oc1',
'ph2',
'ru',
'sg2',
'th2',
'tr1',
'tw2',
'vn2',
] as const;
export type RiotPlatformRoute = (typeof RIOT_PLATFORM_ROUTES)[number];
export type RiotMatchType = 'ranked' | 'normal' | 'tourney' | 'tutorial';
export interface RiotAccountRegionDto {
puuid: string;
game: string;
region: RiotPlatformRoute;
}
export interface RiotAccountApiResponse {
puuid: string;
gameName?: string;
@@ -15,6 +48,7 @@ export interface RiotAccountDto {
export interface RiotRequestOptions {
region?: RiotRegionalRoute;
platform?: RiotPlatformRoute;
query?: Record<string, string | number | boolean | undefined>;
signal?: AbortSignal;
}
@@ -38,6 +72,54 @@ export interface RiotMatchLookupOptions {
signal?: AbortSignal;
}
export interface RiotPlatformLookupOptions {
platform?: RiotPlatformRoute;
signal?: AbortSignal;
}
// Summoner-V4 by-puuid 응답 (간소화 — 실제 응답에 id 가 빠질 수 있어 optional 처리)
export interface RiotSummonerDto {
puuid: string;
profileIconId: number;
revisionDate: number;
summonerLevel: number;
id?: string;
accountId?: string;
}
// League-V4 entries by-puuid 응답
export interface RiotLeagueEntryDto {
leagueId: string;
queueType: string;
tier: string;
rank: string;
puuid: string;
leaguePoints: number;
wins: number;
losses: number;
veteran?: boolean;
inactive?: boolean;
freshBlood?: boolean;
hotStreak?: boolean;
miniSeries?: Record<string, unknown>;
}
// Champion-Mastery-V4 by-puuid 응답
export interface RiotChampionMasteryDto extends Record<string, unknown> {
puuid: string;
championId: number;
championLevel: number;
championPoints: number;
lastPlayTime?: number;
championPointsSinceLastLevel?: number;
championPointsUntilNextLevel?: number;
markRequiredForNextLevel?: number;
tokensEarned?: number;
championSeasonMilestone?: number;
milestoneGrades?: string[];
nextSeasonMilestone?: Record<string, unknown>;
}
export interface RiotMatchIdsLookupOptions extends RiotMatchLookupOptions {
start?: number;
count?: number;