feat: riot api
This commit is contained in:
1 parent
e3da5d83b6
commit
14626516ff
6 files changed
+1012
-1
No files matched your search
@@ -1,9 +1,19 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { GlobalModule } from './modules/global/global.module';
|
||||
import { RiotModule } from './modules/riot/riot.module';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
envFilePath: ['../project.env', 'project.env'],
|
||||
}),
|
||||
GlobalModule,
|
||||
RiotModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { RiotClientService } from './riot.client.service';
|
||||
import {
|
||||
RiotAccountDto,
|
||||
RiotAccountLookupOptions,
|
||||
} from './riot.types';
|
||||
|
||||
@Injectable()
|
||||
export class RiotAccountService {
|
||||
constructor(private readonly riotClientService: RiotClientService) {}
|
||||
|
||||
public async getByRiotId(
|
||||
gameName: string,
|
||||
tagLine: string,
|
||||
options: RiotAccountLookupOptions = {},
|
||||
): Promise<RiotAccountDto> {
|
||||
return this.riotClientService.get<RiotAccountDto>(
|
||||
`/riot/account/v1/accounts/by-riot-id/${encodeURIComponent(gameName)}/${encodeURIComponent(tagLine)}`,
|
||||
{
|
||||
region: options.region,
|
||||
signal: options.signal,
|
||||
},
|
||||
parseRiotAccountDto,
|
||||
);
|
||||
}
|
||||
|
||||
public async getByPuuid(
|
||||
puuid: string,
|
||||
options: RiotAccountLookupOptions = {},
|
||||
): Promise<RiotAccountDto> {
|
||||
return this.riotClientService.get<RiotAccountDto>(
|
||||
`/riot/account/v1/accounts/by-puuid/${encodeURIComponent(puuid)}`,
|
||||
{
|
||||
region: options.region,
|
||||
signal: options.signal,
|
||||
},
|
||||
parseRiotAccountDto,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function parseRiotAccountDto(value: unknown): RiotAccountDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError('Riot account response must be an object.');
|
||||
}
|
||||
|
||||
const puuid = value.puuid;
|
||||
const gameName = value.gameName;
|
||||
const tagLine = value.tagLine;
|
||||
|
||||
if (!isNonEmptyString(puuid)) {
|
||||
throw new TypeError('Riot account response is missing a valid puuid.');
|
||||
}
|
||||
|
||||
if (!isOptionalString(gameName)) {
|
||||
throw new TypeError('Riot account response has an invalid gameName.');
|
||||
}
|
||||
|
||||
if (!isOptionalString(tagLine)) {
|
||||
throw new TypeError('Riot account response has an invalid tagLine.');
|
||||
}
|
||||
|
||||
return {
|
||||
puuid,
|
||||
gameName: gameName ?? null,
|
||||
tagLine: tagLine ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
|
||||
function isNonEmptyString(value: unknown): value is string {
|
||||
return typeof value === 'string' && value.length > 0;
|
||||
}
|
||||
|
||||
function isOptionalString(value: unknown): value is string | undefined {
|
||||
return value === undefined || typeof value === 'string';
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { RiotClientService } from './riot.client.service';
|
||||
import {
|
||||
RiotMatchBanDto,
|
||||
RiotMatchDto,
|
||||
RiotMatchIdsLookupOptions,
|
||||
RiotMatchInfoDto,
|
||||
RiotMatchLookupOptions,
|
||||
RiotMatchMetadataDto,
|
||||
RiotMatchObjectiveDto,
|
||||
RiotMatchObjectivesDto,
|
||||
RiotMatchParticipantDto,
|
||||
RiotMatchPerksDto,
|
||||
RiotMatchPerkStyleDto,
|
||||
RiotMatchPerkStyleSelectionDto,
|
||||
RiotMatchStatPerksDto,
|
||||
RiotMatchTeamDto,
|
||||
RiotMatchType,
|
||||
} from './riot.types';
|
||||
|
||||
const RIOT_MATCH_TYPES: RiotMatchType[] = [
|
||||
'ranked',
|
||||
'normal',
|
||||
'tourney',
|
||||
'tutorial',
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class RiotMatchService {
|
||||
constructor(private readonly riotClientService: RiotClientService) {}
|
||||
|
||||
public async getMatchIdsByPuuid(
|
||||
puuid: string,
|
||||
options: RiotMatchIdsLookupOptions = {},
|
||||
): Promise<string[]> {
|
||||
validateMatchIdsLookupOptions(options);
|
||||
|
||||
return this.riotClientService.get<string[]>(
|
||||
`/lol/match/v5/matches/by-puuid/${encodeURIComponent(puuid)}/ids`,
|
||||
{
|
||||
region: options.region,
|
||||
signal: options.signal,
|
||||
query: {
|
||||
start: options.start,
|
||||
count: options.count,
|
||||
queue: options.queue,
|
||||
type: options.type,
|
||||
startTime: options.startTime,
|
||||
endTime: options.endTime,
|
||||
},
|
||||
},
|
||||
parseMatchIdsResponse,
|
||||
);
|
||||
}
|
||||
|
||||
public async getMatch(
|
||||
matchId: string,
|
||||
options: RiotMatchLookupOptions = {},
|
||||
): Promise<RiotMatchDto> {
|
||||
return this.riotClientService.get<RiotMatchDto>(
|
||||
`/lol/match/v5/matches/${encodeURIComponent(matchId)}`,
|
||||
{
|
||||
region: options.region,
|
||||
signal: options.signal,
|
||||
},
|
||||
parseMatchResponse,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function validateMatchIdsLookupOptions(
|
||||
options: RiotMatchIdsLookupOptions,
|
||||
): void {
|
||||
assertOptionalNonNegativeInteger(options.start, 'start');
|
||||
assertOptionalRange(options.count, 'count', 0, 100);
|
||||
assertOptionalNonNegativeInteger(options.queue, 'queue');
|
||||
assertOptionalNonNegativeInteger(options.startTime, 'startTime');
|
||||
assertOptionalNonNegativeInteger(options.endTime, 'endTime');
|
||||
|
||||
if (options.type !== undefined && !RIOT_MATCH_TYPES.includes(options.type)) {
|
||||
throw new RangeError(
|
||||
`type must be one of: ${RIOT_MATCH_TYPES.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
options.startTime !== undefined &&
|
||||
options.endTime !== undefined &&
|
||||
options.startTime > options.endTime
|
||||
) {
|
||||
throw new RangeError('startTime must be less than or equal to endTime.');
|
||||
}
|
||||
}
|
||||
|
||||
function parseMatchIdsResponse(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new TypeError('Riot match ids response must be an array.');
|
||||
}
|
||||
|
||||
if (!value.every(isNonEmptyString)) {
|
||||
throw new TypeError('Riot match ids response must contain only strings.');
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseMatchResponse(value: unknown): RiotMatchDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError('Riot match response must be an object.');
|
||||
}
|
||||
|
||||
return {
|
||||
metadata: parseMatchMetadata(value.metadata),
|
||||
info: parseMatchInfo(value.info),
|
||||
};
|
||||
}
|
||||
|
||||
function parseMatchMetadata(value: unknown): RiotMatchMetadataDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError('Riot match metadata must be an object.');
|
||||
}
|
||||
|
||||
const dataVersion = value.dataVersion;
|
||||
const matchId = value.matchId;
|
||||
const participants = value.participants;
|
||||
|
||||
if (!isNonEmptyString(dataVersion)) {
|
||||
throw new TypeError('Riot match metadata.dataVersion must be a string.');
|
||||
}
|
||||
|
||||
if (!isNonEmptyString(matchId)) {
|
||||
throw new TypeError('Riot match metadata.matchId must be a string.');
|
||||
}
|
||||
|
||||
if (!Array.isArray(participants) || !participants.every(isNonEmptyString)) {
|
||||
throw new TypeError(
|
||||
'Riot match metadata.participants must be an array of strings.',
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
dataVersion,
|
||||
matchId,
|
||||
participants,
|
||||
};
|
||||
}
|
||||
|
||||
function parseMatchInfo(value: unknown): RiotMatchInfoDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError('Riot match info must be an object.');
|
||||
}
|
||||
|
||||
const participants = value.participants;
|
||||
const teams = value.teams;
|
||||
|
||||
if (!Array.isArray(participants)) {
|
||||
throw new TypeError('Riot match info.participants must be an array.');
|
||||
}
|
||||
|
||||
if (!Array.isArray(teams)) {
|
||||
throw new TypeError('Riot match info.teams must be an array.');
|
||||
}
|
||||
|
||||
const gameCreation = requireNumber(value.gameCreation, 'info.gameCreation');
|
||||
const gameDuration = requireNumber(value.gameDuration, 'info.gameDuration');
|
||||
const gameId = requireNumber(value.gameId, 'info.gameId');
|
||||
const gameMode = requireString(value.gameMode, 'info.gameMode');
|
||||
const gameName = requireString(value.gameName, 'info.gameName');
|
||||
const gameStartTimestamp = requireNumber(
|
||||
value.gameStartTimestamp,
|
||||
'info.gameStartTimestamp',
|
||||
);
|
||||
const gameType = requireString(value.gameType, 'info.gameType');
|
||||
const gameVersion = requireString(value.gameVersion, 'info.gameVersion');
|
||||
const mapId = requireNumber(value.mapId, 'info.mapId');
|
||||
const platformId = requireString(value.platformId, 'info.platformId');
|
||||
const queueId = requireNumber(value.queueId, 'info.queueId');
|
||||
const gameEndTimestamp = optionalNumber(
|
||||
value.gameEndTimestamp,
|
||||
'info.gameEndTimestamp',
|
||||
);
|
||||
const tournamentCode = optionalString(
|
||||
value.tournamentCode,
|
||||
'info.tournamentCode',
|
||||
);
|
||||
const endOfGameResult = optionalString(
|
||||
value.endOfGameResult,
|
||||
'info.endOfGameResult',
|
||||
);
|
||||
|
||||
return {
|
||||
...value,
|
||||
endOfGameResult,
|
||||
gameCreation,
|
||||
gameDuration,
|
||||
gameEndTimestamp,
|
||||
gameId,
|
||||
gameMode,
|
||||
gameName,
|
||||
gameStartTimestamp,
|
||||
gameType,
|
||||
gameVersion,
|
||||
mapId,
|
||||
participants: participants.map((participant, index) =>
|
||||
parseParticipant(participant, index),
|
||||
),
|
||||
platformId,
|
||||
queueId,
|
||||
teams: teams.map((team, index) => parseTeam(team, index)),
|
||||
tournamentCode,
|
||||
};
|
||||
}
|
||||
|
||||
function parseParticipant(
|
||||
value: unknown,
|
||||
index: number,
|
||||
): RiotMatchParticipantDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(`participants[${index}] must be an object.`);
|
||||
}
|
||||
|
||||
return {
|
||||
...value,
|
||||
assists: requireNumber(value.assists, `participants[${index}].assists`),
|
||||
champExperience: requireNumber(
|
||||
value.champExperience,
|
||||
`participants[${index}].champExperience`,
|
||||
),
|
||||
champLevel: requireNumber(
|
||||
value.champLevel,
|
||||
`participants[${index}].champLevel`,
|
||||
),
|
||||
championId: requireNumber(
|
||||
value.championId,
|
||||
`participants[${index}].championId`,
|
||||
),
|
||||
championName: requireString(
|
||||
value.championName,
|
||||
`participants[${index}].championName`,
|
||||
),
|
||||
deaths: requireNumber(value.deaths, `participants[${index}].deaths`),
|
||||
goldEarned: requireNumber(
|
||||
value.goldEarned,
|
||||
`participants[${index}].goldEarned`,
|
||||
),
|
||||
goldSpent: requireNumber(
|
||||
value.goldSpent,
|
||||
`participants[${index}].goldSpent`,
|
||||
),
|
||||
individualPosition: requireString(
|
||||
value.individualPosition,
|
||||
`participants[${index}].individualPosition`,
|
||||
),
|
||||
item0: requireNumber(value.item0, `participants[${index}].item0`),
|
||||
item1: requireNumber(value.item1, `participants[${index}].item1`),
|
||||
item2: requireNumber(value.item2, `participants[${index}].item2`),
|
||||
item3: requireNumber(value.item3, `participants[${index}].item3`),
|
||||
item4: requireNumber(value.item4, `participants[${index}].item4`),
|
||||
item5: requireNumber(value.item5, `participants[${index}].item5`),
|
||||
item6: requireNumber(value.item6, `participants[${index}].item6`),
|
||||
kills: requireNumber(value.kills, `participants[${index}].kills`),
|
||||
neutralMinionsKilled: requireNumber(
|
||||
value.neutralMinionsKilled,
|
||||
`participants[${index}].neutralMinionsKilled`,
|
||||
),
|
||||
participantId: requireNumber(
|
||||
value.participantId,
|
||||
`participants[${index}].participantId`,
|
||||
),
|
||||
perks: parsePerks(value.perks, index),
|
||||
puuid: requireString(value.puuid, `participants[${index}].puuid`),
|
||||
riotIdGameName: optionalString(
|
||||
value.riotIdGameName,
|
||||
`participants[${index}].riotIdGameName`,
|
||||
),
|
||||
riotIdTagLine: optionalString(
|
||||
value.riotIdTagLine,
|
||||
`participants[${index}].riotIdTagLine`,
|
||||
),
|
||||
summoner1Id: requireNumber(
|
||||
value.summoner1Id,
|
||||
`participants[${index}].summoner1Id`,
|
||||
),
|
||||
summoner2Id: requireNumber(
|
||||
value.summoner2Id,
|
||||
`participants[${index}].summoner2Id`,
|
||||
),
|
||||
summonerId: requireString(
|
||||
value.summonerId,
|
||||
`participants[${index}].summonerId`,
|
||||
),
|
||||
summonerLevel: requireNumber(
|
||||
value.summonerLevel,
|
||||
`participants[${index}].summonerLevel`,
|
||||
),
|
||||
summonerName: requireString(
|
||||
value.summonerName,
|
||||
`participants[${index}].summonerName`,
|
||||
),
|
||||
teamId: requireNumber(value.teamId, `participants[${index}].teamId`),
|
||||
teamPosition: requireString(
|
||||
value.teamPosition,
|
||||
`participants[${index}].teamPosition`,
|
||||
),
|
||||
timePlayed: requireNumber(
|
||||
value.timePlayed,
|
||||
`participants[${index}].timePlayed`,
|
||||
),
|
||||
totalDamageDealtToChampions: requireNumber(
|
||||
value.totalDamageDealtToChampions,
|
||||
`participants[${index}].totalDamageDealtToChampions`,
|
||||
),
|
||||
totalDamageTaken: requireNumber(
|
||||
value.totalDamageTaken,
|
||||
`participants[${index}].totalDamageTaken`,
|
||||
),
|
||||
totalMinionsKilled: requireNumber(
|
||||
value.totalMinionsKilled,
|
||||
`participants[${index}].totalMinionsKilled`,
|
||||
),
|
||||
visionScore: requireNumber(
|
||||
value.visionScore,
|
||||
`participants[${index}].visionScore`,
|
||||
),
|
||||
wardsKilled: requireNumber(
|
||||
value.wardsKilled,
|
||||
`participants[${index}].wardsKilled`,
|
||||
),
|
||||
wardsPlaced: requireNumber(
|
||||
value.wardsPlaced,
|
||||
`participants[${index}].wardsPlaced`,
|
||||
),
|
||||
win: requireBoolean(value.win, `participants[${index}].win`),
|
||||
};
|
||||
}
|
||||
|
||||
function parsePerks(value: unknown, participantIndex: number): RiotMatchPerksDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(
|
||||
`participants[${participantIndex}].perks must be an object.`,
|
||||
);
|
||||
}
|
||||
|
||||
const styles = value.styles;
|
||||
if (!Array.isArray(styles)) {
|
||||
throw new TypeError(
|
||||
`participants[${participantIndex}].perks.styles must be an array.`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
statPerks: parseStatPerks(value.statPerks, participantIndex),
|
||||
styles: styles.map((style, styleIndex) =>
|
||||
parsePerkStyle(style, participantIndex, styleIndex),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function parseStatPerks(
|
||||
value: unknown,
|
||||
participantIndex: number,
|
||||
): RiotMatchStatPerksDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(
|
||||
`participants[${participantIndex}].perks.statPerks must be an object.`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
defense: requireNumber(
|
||||
value.defense,
|
||||
`participants[${participantIndex}].perks.statPerks.defense`,
|
||||
),
|
||||
flex: requireNumber(
|
||||
value.flex,
|
||||
`participants[${participantIndex}].perks.statPerks.flex`,
|
||||
),
|
||||
offense: requireNumber(
|
||||
value.offense,
|
||||
`participants[${participantIndex}].perks.statPerks.offense`,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function parsePerkStyle(
|
||||
value: unknown,
|
||||
participantIndex: number,
|
||||
styleIndex: number,
|
||||
): RiotMatchPerkStyleDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(
|
||||
`participants[${participantIndex}].perks.styles[${styleIndex}] must be an object.`,
|
||||
);
|
||||
}
|
||||
|
||||
const selections = value.selections;
|
||||
if (!Array.isArray(selections)) {
|
||||
throw new TypeError(
|
||||
`participants[${participantIndex}].perks.styles[${styleIndex}].selections must be an array.`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
description: requireString(
|
||||
value.description,
|
||||
`participants[${participantIndex}].perks.styles[${styleIndex}].description`,
|
||||
),
|
||||
selections: selections.map((selection, selectionIndex) =>
|
||||
parsePerkSelection(
|
||||
selection,
|
||||
participantIndex,
|
||||
styleIndex,
|
||||
selectionIndex,
|
||||
),
|
||||
),
|
||||
style: requireNumber(
|
||||
value.style,
|
||||
`participants[${participantIndex}].perks.styles[${styleIndex}].style`,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function parsePerkSelection(
|
||||
value: unknown,
|
||||
participantIndex: number,
|
||||
styleIndex: number,
|
||||
selectionIndex: number,
|
||||
): RiotMatchPerkStyleSelectionDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(
|
||||
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}] must be an object.`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
perk: requireNumber(
|
||||
value.perk,
|
||||
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].perk`,
|
||||
),
|
||||
var1: requireNumber(
|
||||
value.var1,
|
||||
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var1`,
|
||||
),
|
||||
var2: requireNumber(
|
||||
value.var2,
|
||||
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var2`,
|
||||
),
|
||||
var3: requireNumber(
|
||||
value.var3,
|
||||
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var3`,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function parseTeam(value: unknown, index: number): RiotMatchTeamDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(`teams[${index}] must be an object.`);
|
||||
}
|
||||
|
||||
const bans = value.bans;
|
||||
if (!Array.isArray(bans)) {
|
||||
throw new TypeError(`teams[${index}].bans must be an array.`);
|
||||
}
|
||||
|
||||
return {
|
||||
...value,
|
||||
bans: bans.map((ban, banIndex) => parseBan(ban, index, banIndex)),
|
||||
objectives: parseObjectives(value.objectives, index),
|
||||
teamId: requireNumber(value.teamId, `teams[${index}].teamId`),
|
||||
win: requireBoolean(value.win, `teams[${index}].win`),
|
||||
};
|
||||
}
|
||||
|
||||
function parseBan(
|
||||
value: unknown,
|
||||
teamIndex: number,
|
||||
banIndex: number,
|
||||
): RiotMatchBanDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(`teams[${teamIndex}].bans[${banIndex}] must be an object.`);
|
||||
}
|
||||
|
||||
return {
|
||||
championId: requireNumber(
|
||||
value.championId,
|
||||
`teams[${teamIndex}].bans[${banIndex}].championId`,
|
||||
),
|
||||
pickTurn: requireNumber(
|
||||
value.pickTurn,
|
||||
`teams[${teamIndex}].bans[${banIndex}].pickTurn`,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function parseObjectives(
|
||||
value: unknown,
|
||||
teamIndex: number,
|
||||
): RiotMatchObjectivesDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(`teams[${teamIndex}].objectives must be an object.`);
|
||||
}
|
||||
|
||||
return {
|
||||
baron: parseObjective(value.baron, teamIndex, 'baron'),
|
||||
champion: parseObjective(value.champion, teamIndex, 'champion'),
|
||||
dragon: parseObjective(value.dragon, teamIndex, 'dragon'),
|
||||
inhibitor: parseObjective(value.inhibitor, teamIndex, 'inhibitor'),
|
||||
riftHerald: parseObjective(value.riftHerald, teamIndex, 'riftHerald'),
|
||||
tower: parseObjective(value.tower, teamIndex, 'tower'),
|
||||
};
|
||||
}
|
||||
|
||||
function parseObjective(
|
||||
value: unknown,
|
||||
teamIndex: number,
|
||||
key: keyof RiotMatchObjectivesDto,
|
||||
): RiotMatchObjectiveDto {
|
||||
if (!isRecord(value)) {
|
||||
throw new TypeError(`teams[${teamIndex}].objectives.${key} must be an object.`);
|
||||
}
|
||||
|
||||
return {
|
||||
first: requireBoolean(
|
||||
value.first,
|
||||
`teams[${teamIndex}].objectives.${key}.first`,
|
||||
),
|
||||
kills: requireNumber(
|
||||
value.kills,
|
||||
`teams[${teamIndex}].objectives.${key}.kills`,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function requireString(value: unknown, path: string): string {
|
||||
if (!isNonEmptyString(value)) {
|
||||
throw new TypeError(`${path} must be a non-empty string.`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function optionalString(value: unknown, path: string): string | undefined {
|
||||
if (value === undefined || value === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (typeof value !== 'string') {
|
||||
throw new TypeError(`${path} must be a string when present.`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function requireNumber(value: unknown, path: string): number {
|
||||
if (!isFiniteNumber(value)) {
|
||||
throw new TypeError(`${path} must be a finite number.`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function optionalNumber(value: unknown, path: string): number | undefined {
|
||||
if (value === undefined || value === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!isFiniteNumber(value)) {
|
||||
throw new TypeError(`${path} must be a finite number when present.`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function requireBoolean(value: unknown, path: string): boolean {
|
||||
if (typeof value !== 'boolean') {
|
||||
throw new TypeError(`${path} must be a boolean.`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function assertOptionalNonNegativeInteger(
|
||||
value: number | undefined,
|
||||
fieldName: string,
|
||||
): void {
|
||||
if (value === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Number.isInteger(value) || value < 0) {
|
||||
throw new RangeError(`${fieldName} must be a non-negative integer.`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertOptionalRange(
|
||||
value: number | undefined,
|
||||
fieldName: string,
|
||||
min: number,
|
||||
max: number,
|
||||
): void {
|
||||
if (value === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Number.isInteger(value) || value < min || value > max) {
|
||||
throw new RangeError(
|
||||
`${fieldName} must be an integer between ${min} and ${max}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
|
||||
function isFiniteNumber(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isFinite(value);
|
||||
}
|
||||
|
||||
function isNonEmptyString(value: unknown): value is string {
|
||||
return typeof value === 'string' && value.length > 0;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import {
|
||||
RiotApiErrorBody,
|
||||
RiotRegionalRoute,
|
||||
RiotRequestOptions,
|
||||
RiotResponseParser,
|
||||
} from './riot.types';
|
||||
|
||||
const RIOT_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',
|
||||
};
|
||||
|
||||
export class RiotApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number,
|
||||
public readonly url: string,
|
||||
public readonly body?: RiotApiErrorBody,
|
||||
public readonly retryAfterSeconds?: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RiotClientService {
|
||||
private readonly logger = new Logger(RiotClientService.name);
|
||||
|
||||
constructor(private readonly secretService: SecretService) {}
|
||||
|
||||
public async get<T>(
|
||||
path: string,
|
||||
options: RiotRequestOptions = {},
|
||||
parser?: RiotResponseParser<T>,
|
||||
): Promise<T> {
|
||||
const apiKey = await this.secretService.get<string>('RIOT_API_KEY');
|
||||
const url = this.buildUrl(path, options);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'X-Riot-Token': apiKey,
|
||||
},
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await this.createApiError(response, url);
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as unknown;
|
||||
|
||||
if (parser) {
|
||||
return parser(payload);
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
}
|
||||
|
||||
private buildUrl(path: string, options: RiotRequestOptions): string {
|
||||
const region = options.region ?? 'asia';
|
||||
const baseUrl = RIOT_BASE_URLS[region];
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
||||
const url = new URL(`${baseUrl}${normalizedPath}`);
|
||||
|
||||
if (options.query) {
|
||||
for (const [key, value] of Object.entries(options.query)) {
|
||||
if (value === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
url.searchParams.set(key, String(value));
|
||||
}
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
private async createApiError(
|
||||
response: Response,
|
||||
url: string,
|
||||
): Promise<RiotApiError> {
|
||||
let body: RiotApiErrorBody | undefined;
|
||||
|
||||
try {
|
||||
body = (await response.json()) as RiotApiErrorBody;
|
||||
} catch {
|
||||
body = undefined;
|
||||
}
|
||||
|
||||
const message =
|
||||
body?.status?.message ??
|
||||
`Riot API request failed with status ${response.status}`;
|
||||
const retryAfterHeader = response.headers.get('Retry-After');
|
||||
const retryAfterSeconds = retryAfterHeader
|
||||
? Number(retryAfterHeader)
|
||||
: undefined;
|
||||
|
||||
this.logger.warn(`${message} (${response.status}) ${url}`);
|
||||
|
||||
return new RiotApiError(
|
||||
message,
|
||||
response.status,
|
||||
url,
|
||||
body,
|
||||
Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : undefined,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { SecretModule } from '../global/secret/secret.module';
|
||||
import { RiotAccountService } from './riot-account.service';
|
||||
import { RiotClientService } from './riot.client.service';
|
||||
import { RiotMatchService } from './riot-match.service';
|
||||
|
||||
@Module({
|
||||
imports: [SecretModule],
|
||||
providers: [RiotClientService, RiotAccountService, RiotMatchService],
|
||||
exports: [RiotClientService, RiotAccountService, RiotMatchService],
|
||||
})
|
||||
export class RiotModule {}
|
||||
@@ -0,0 +1,169 @@
|
||||
export type RiotRegionalRoute = 'americas' | 'asia' | 'europe' | 'sea';
|
||||
export type RiotMatchType = 'ranked' | 'normal' | 'tourney' | 'tutorial';
|
||||
|
||||
export interface RiotAccountApiResponse {
|
||||
puuid: string;
|
||||
gameName?: string;
|
||||
tagLine?: string;
|
||||
}
|
||||
|
||||
export interface RiotAccountDto {
|
||||
puuid: string;
|
||||
gameName: string | null;
|
||||
tagLine: string | null;
|
||||
}
|
||||
|
||||
export interface RiotRequestOptions {
|
||||
region?: RiotRegionalRoute;
|
||||
query?: Record<string, string | number | boolean | undefined>;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export type RiotResponseParser<T> = (value: unknown) => T;
|
||||
|
||||
export interface RiotApiErrorBody {
|
||||
status?: {
|
||||
message?: string;
|
||||
status_code?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface RiotAccountLookupOptions {
|
||||
region?: RiotRegionalRoute;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface RiotMatchLookupOptions {
|
||||
region?: RiotRegionalRoute;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface RiotMatchIdsLookupOptions extends RiotMatchLookupOptions {
|
||||
start?: number;
|
||||
count?: number;
|
||||
queue?: number;
|
||||
type?: RiotMatchType;
|
||||
startTime?: number;
|
||||
endTime?: number;
|
||||
}
|
||||
|
||||
export interface RiotMatchDto {
|
||||
metadata: RiotMatchMetadataDto;
|
||||
info: RiotMatchInfoDto;
|
||||
}
|
||||
|
||||
export interface RiotMatchMetadataDto {
|
||||
dataVersion: string;
|
||||
matchId: string;
|
||||
participants: string[];
|
||||
}
|
||||
|
||||
export interface RiotMatchInfoDto extends Record<string, unknown> {
|
||||
endOfGameResult?: string;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
gameEndTimestamp?: number;
|
||||
gameId: number;
|
||||
gameMode: string;
|
||||
gameName: string;
|
||||
gameStartTimestamp: number;
|
||||
gameType: string;
|
||||
gameVersion: string;
|
||||
mapId: number;
|
||||
participants: RiotMatchParticipantDto[];
|
||||
platformId: string;
|
||||
queueId: number;
|
||||
teams: RiotMatchTeamDto[];
|
||||
tournamentCode?: string;
|
||||
}
|
||||
|
||||
export interface RiotMatchParticipantDto extends Record<string, unknown> {
|
||||
assists: number;
|
||||
champExperience: number;
|
||||
champLevel: number;
|
||||
championId: number;
|
||||
championName: string;
|
||||
deaths: number;
|
||||
goldEarned: number;
|
||||
goldSpent: number;
|
||||
individualPosition: string;
|
||||
item0: number;
|
||||
item1: number;
|
||||
item2: number;
|
||||
item3: number;
|
||||
item4: number;
|
||||
item5: number;
|
||||
item6: number;
|
||||
kills: number;
|
||||
neutralMinionsKilled: number;
|
||||
participantId: number;
|
||||
perks: RiotMatchPerksDto;
|
||||
puuid: string;
|
||||
riotIdGameName?: string;
|
||||
riotIdTagLine?: string;
|
||||
summoner1Id: number;
|
||||
summoner2Id: number;
|
||||
summonerId: string;
|
||||
summonerLevel: number;
|
||||
summonerName: string;
|
||||
teamId: number;
|
||||
teamPosition: string;
|
||||
timePlayed: number;
|
||||
totalDamageDealtToChampions: number;
|
||||
totalDamageTaken: number;
|
||||
totalMinionsKilled: number;
|
||||
visionScore: number;
|
||||
wardsKilled: number;
|
||||
wardsPlaced: number;
|
||||
win: boolean;
|
||||
}
|
||||
|
||||
export interface RiotMatchPerksDto {
|
||||
statPerks: RiotMatchStatPerksDto;
|
||||
styles: RiotMatchPerkStyleDto[];
|
||||
}
|
||||
|
||||
export interface RiotMatchStatPerksDto {
|
||||
defense: number;
|
||||
flex: number;
|
||||
offense: number;
|
||||
}
|
||||
|
||||
export interface RiotMatchPerkStyleDto {
|
||||
description: string;
|
||||
selections: RiotMatchPerkStyleSelectionDto[];
|
||||
style: number;
|
||||
}
|
||||
|
||||
export interface RiotMatchPerkStyleSelectionDto {
|
||||
perk: number;
|
||||
var1: number;
|
||||
var2: number;
|
||||
var3: number;
|
||||
}
|
||||
|
||||
export interface RiotMatchTeamDto extends Record<string, unknown> {
|
||||
bans: RiotMatchBanDto[];
|
||||
objectives: RiotMatchObjectivesDto;
|
||||
teamId: number;
|
||||
win: boolean;
|
||||
}
|
||||
|
||||
export interface RiotMatchBanDto {
|
||||
championId: number;
|
||||
pickTurn: number;
|
||||
}
|
||||
|
||||
export interface RiotMatchObjectivesDto {
|
||||
baron: RiotMatchObjectiveDto;
|
||||
champion: RiotMatchObjectiveDto;
|
||||
dragon: RiotMatchObjectiveDto;
|
||||
inhibitor: RiotMatchObjectiveDto;
|
||||
riftHerald: RiotMatchObjectiveDto;
|
||||
tower: RiotMatchObjectiveDto;
|
||||
}
|
||||
|
||||
export interface RiotMatchObjectiveDto {
|
||||
first: boolean;
|
||||
kills: number;
|
||||
}
|
||||
Reference in new issue
Block a user