.
This commit is contained in:
1 parent
905bbcc6dd
commit
2472f865ad
14 files changed
+825
-18
No files matched your search
@@ -37,6 +37,7 @@
|
||||
"jose": "^6.2.2",
|
||||
"mongoose": "^9.4.1",
|
||||
"nats": "^2.29.3",
|
||||
"redis": "^5.12.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"socket.io": "^4.8.3",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export const GARNET_CLIENT = Symbol('GARNET_CLIENT');
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Logger, Module } from '@nestjs/common';
|
||||
import { createClient } from 'redis';
|
||||
import { SecretModule } from '../secret/secret.module';
|
||||
import { SecretService } from '../secret/secret.service';
|
||||
import { GARNET_CLIENT } from './garnet.constants';
|
||||
import { GarnetService, type GarnetRedisClient } from './garnet.service';
|
||||
|
||||
function normalizeGarnetUrl(endpoint: string): string {
|
||||
const trimmed = endpoint.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error('GARNET_ENDPOINT cannot be empty');
|
||||
}
|
||||
if (/^redis(s)?:\/\//iu.test(trimmed)) {
|
||||
return trimmed;
|
||||
}
|
||||
return `redis://${trimmed}`;
|
||||
}
|
||||
|
||||
@Module({
|
||||
imports: [SecretModule],
|
||||
providers: [
|
||||
{
|
||||
provide: GARNET_CLIENT,
|
||||
inject: [SecretService],
|
||||
useFactory: async (
|
||||
secretService: SecretService,
|
||||
): Promise<GarnetRedisClient> => {
|
||||
await secretService.ready();
|
||||
|
||||
const [endpoint, username, password] = await Promise.all([
|
||||
secretService.get<string>('GARNET_ENDPOINT'),
|
||||
secretService.get<string>('GARNET_USERID'),
|
||||
secretService.get<string>('GARNET_PASSWORD'),
|
||||
]);
|
||||
|
||||
const logger = new Logger('GarnetClient');
|
||||
const client = createClient({
|
||||
url: normalizeGarnetUrl(endpoint),
|
||||
username,
|
||||
password,
|
||||
});
|
||||
|
||||
client.on('error', (error) => {
|
||||
logger.error(`Garnet client error: ${error?.message ?? error}`);
|
||||
});
|
||||
|
||||
await client.connect();
|
||||
logger.log('Garnet connected');
|
||||
|
||||
return client;
|
||||
},
|
||||
},
|
||||
GarnetService,
|
||||
],
|
||||
exports: [GarnetService, GARNET_CLIENT],
|
||||
})
|
||||
export class GarnetModule {}
|
||||
@@ -0,0 +1,90 @@
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
} from '@nestjs/common';
|
||||
import type { createClient } from 'redis';
|
||||
import { GARNET_CLIENT } from './garnet.constants';
|
||||
|
||||
export type GarnetRedisClient = ReturnType<typeof createClient>;
|
||||
|
||||
@Injectable()
|
||||
export class GarnetService implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(GarnetService.name);
|
||||
|
||||
constructor(
|
||||
@Inject(GARNET_CLIENT) private readonly client: GarnetRedisClient,
|
||||
) {}
|
||||
|
||||
async onModuleDestroy() {
|
||||
try {
|
||||
await this.client.quit();
|
||||
} catch {
|
||||
this.client.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
public raw(): GarnetRedisClient {
|
||||
return this.client;
|
||||
}
|
||||
|
||||
public async getJson<T>(key: string): Promise<T | null> {
|
||||
const raw = await this.client.get(key);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return JSON.parse(raw) as T;
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Failed to JSON.parse cached value for key="${key}": ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async setJson(
|
||||
key: string,
|
||||
value: unknown,
|
||||
ttlSeconds?: number,
|
||||
): Promise<void> {
|
||||
const serialized = JSON.stringify(value);
|
||||
if (ttlSeconds && ttlSeconds > 0) {
|
||||
await this.client.set(key, serialized, { EX: ttlSeconds });
|
||||
return;
|
||||
}
|
||||
await this.client.set(key, serialized);
|
||||
}
|
||||
|
||||
public async getString(key: string): Promise<string | null> {
|
||||
return this.client.get(key);
|
||||
}
|
||||
|
||||
public async setString(
|
||||
key: string,
|
||||
value: string,
|
||||
ttlSeconds?: number,
|
||||
): Promise<void> {
|
||||
if (ttlSeconds && ttlSeconds > 0) {
|
||||
await this.client.set(key, value, { EX: ttlSeconds });
|
||||
return;
|
||||
}
|
||||
await this.client.set(key, value);
|
||||
}
|
||||
|
||||
public async setStringIfAbsent(
|
||||
key: string,
|
||||
value: string,
|
||||
ttlSeconds?: number,
|
||||
): Promise<boolean> {
|
||||
const options: { EX?: number; NX: true } = { NX: true };
|
||||
if (ttlSeconds && ttlSeconds > 0) options.EX = ttlSeconds;
|
||||
const result = await this.client.set(key, value, options);
|
||||
return result === 'OK';
|
||||
}
|
||||
|
||||
public async delete(key: string): Promise<number> {
|
||||
return this.client.del(key);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
import { Module, Global } from '@nestjs/common';
|
||||
import { SecretModule } from './secret/secret.module';
|
||||
// import { DatabaseModule } from './database/database.module';
|
||||
import { NatsModule } from './nats/nats.module';
|
||||
import { DatabaseModule } from './database/database.module';
|
||||
// import { DatabaseModule } from './database/database.module';
|
||||
import { GarnetModule } from './garnet/garnet.module';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [SecretModule, NatsModule, DatabaseModule],
|
||||
imports: [SecretModule, NatsModule, DatabaseModule, GarnetModule],
|
||||
providers: [],
|
||||
exports: [SecretModule, NatsModule, DatabaseModule],
|
||||
exports: [SecretModule, NatsModule, DatabaseModule, GarnetModule],
|
||||
})
|
||||
export class GlobalModule {}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||
import {
|
||||
RiotDdragonService,
|
||||
type DdragonManifest,
|
||||
} from './riot-ddragon.service';
|
||||
|
||||
@Controller('riot/ddragon')
|
||||
export class RiotDdragonController {
|
||||
constructor(private readonly ddragonService: RiotDdragonService) {}
|
||||
|
||||
@Get('manifest')
|
||||
@AllowPublicAccess()
|
||||
public async getManifest(
|
||||
@Query('locale') locale?: string,
|
||||
): Promise<DdragonManifest> {
|
||||
return this.ddragonService.getManifest(locale ?? 'ko_KR');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
|
||||
const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com';
|
||||
const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`;
|
||||
const DEFAULT_LOCALE = 'ko_KR';
|
||||
const CACHE_TTL_SECONDS = 24 * 60 * 60;
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
|
||||
export interface DdragonManifest {
|
||||
version: string;
|
||||
cdn: string;
|
||||
locale: string;
|
||||
champions: Record<string, string>;
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
interface ChampionDataEntry {
|
||||
key: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface ChampionDataResponse {
|
||||
data: Record<string, ChampionDataEntry>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RiotDdragonService {
|
||||
private readonly logger = new Logger(RiotDdragonService.name);
|
||||
private inflight = new Map<string, Promise<DdragonManifest>>();
|
||||
|
||||
constructor(private readonly garnetService: GarnetService) {}
|
||||
|
||||
public async getManifest(locale: string = DEFAULT_LOCALE): Promise<DdragonManifest> {
|
||||
const normalizedLocale = normalizeLocale(locale);
|
||||
const cacheKey = manifestCacheKey(normalizedLocale);
|
||||
|
||||
const cached = await this.garnetService.getJson<DdragonManifest>(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
const pending = this.inflight.get(cacheKey);
|
||||
if (pending) return pending;
|
||||
|
||||
const promise = this.buildManifest(normalizedLocale)
|
||||
.then(async (manifest) => {
|
||||
await this.garnetService.setJson(cacheKey, manifest, CACHE_TTL_SECONDS);
|
||||
return manifest;
|
||||
})
|
||||
.finally(() => {
|
||||
this.inflight.delete(cacheKey);
|
||||
});
|
||||
|
||||
this.inflight.set(cacheKey, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
private async buildManifest(locale: string): Promise<DdragonManifest> {
|
||||
const version = await this.fetchLatestVersion();
|
||||
const champions = await this.fetchChampionMap(version, locale);
|
||||
return {
|
||||
version,
|
||||
cdn: DDRAGON_CDN,
|
||||
locale,
|
||||
champions,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchLatestVersion(): Promise<string> {
|
||||
const versions = await this.fetchJson<unknown>(`${DDRAGON_BASE}/api/versions.json`);
|
||||
if (!Array.isArray(versions) || typeof versions[0] !== 'string') {
|
||||
throw new Error('ddragon versions.json response is malformed.');
|
||||
}
|
||||
return versions[0];
|
||||
}
|
||||
|
||||
private async fetchChampionMap(
|
||||
version: string,
|
||||
locale: string,
|
||||
): Promise<Record<string, string>> {
|
||||
const url = `${DDRAGON_CDN}/${version}/data/${locale}/champion.json`;
|
||||
const payload = await this.fetchJson<ChampionDataResponse>(url);
|
||||
if (!payload || typeof payload !== 'object' || !payload.data) {
|
||||
throw new Error(`ddragon champion.json response is malformed (${url}).`);
|
||||
}
|
||||
|
||||
const map: Record<string, string> = {};
|
||||
for (const entry of Object.values(payload.data)) {
|
||||
if (entry?.key && entry.id) {
|
||||
map[entry.key] = entry.id;
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private async fetchJson<T>(url: string): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json' },
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`ddragon request failed (${response.status}): ${url}`,
|
||||
);
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
`ddragon fetch error for ${url}: ${(err as Error)?.message ?? err}`,
|
||||
);
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeLocale(locale: string): string {
|
||||
const trimmed = locale.trim();
|
||||
if (!/^[a-zA-Z]{2}_[a-zA-Z]{2}$/.test(trimmed)) {
|
||||
return DEFAULT_LOCALE;
|
||||
}
|
||||
return `${trimmed.slice(0, 2).toLowerCase()}_${trimmed.slice(3).toUpperCase()}`;
|
||||
}
|
||||
|
||||
function manifestCacheKey(locale: string): string {
|
||||
return `ddragon:manifest:${locale}`;
|
||||
}
|
||||
@@ -4,6 +4,8 @@ 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 { RiotSummonerService } from './riot-summoner.service';
|
||||
@@ -11,7 +13,7 @@ import { RiotWebhookController } from './riot-webhook.controller';
|
||||
|
||||
@Module({
|
||||
imports: [SecretModule],
|
||||
controllers: [RiotWebhookController],
|
||||
controllers: [RiotWebhookController, RiotDdragonController],
|
||||
providers: [
|
||||
RiotClientService,
|
||||
RiotAccountService,
|
||||
@@ -20,6 +22,7 @@ import { RiotWebhookController } from './riot-webhook.controller';
|
||||
RiotLeagueService,
|
||||
RiotChampionMasteryService,
|
||||
RiotAccountEnrichmentService,
|
||||
RiotDdragonService,
|
||||
],
|
||||
exports: [
|
||||
RiotClientService,
|
||||
@@ -29,6 +32,7 @@ import { RiotWebhookController } from './riot-webhook.controller';
|
||||
RiotLeagueService,
|
||||
RiotChampionMasteryService,
|
||||
RiotAccountEnrichmentService,
|
||||
RiotDdragonService,
|
||||
],
|
||||
})
|
||||
export class RiotModule {}
|
||||
@@ -5,11 +5,14 @@ import type {
|
||||
ApiAuction,
|
||||
ApiCommunity,
|
||||
ApiMatch,
|
||||
DdragonManifest,
|
||||
MatchStatus,
|
||||
MatchesResponse,
|
||||
MeResponse,
|
||||
} from './types';
|
||||
|
||||
const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
interface MatchesQueryOptions {
|
||||
status?: MatchStatus;
|
||||
limit?: number;
|
||||
@@ -74,6 +77,20 @@ export function useAuction(
|
||||
});
|
||||
}
|
||||
|
||||
export function useDdragonManifest(locale = 'ko_KR') {
|
||||
return useQuery({
|
||||
queryKey: ['ddragon-manifest', locale],
|
||||
queryFn: () =>
|
||||
apiFetch<DdragonManifest>(
|
||||
`/riot/ddragon/manifest?locale=${encodeURIComponent(locale)}`,
|
||||
),
|
||||
staleTime: DDRAGON_MANIFEST_STALE_MS,
|
||||
gcTime: DDRAGON_MANIFEST_STALE_MS,
|
||||
refetchOnMount: false,
|
||||
refetchOnReconnect: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useMe() {
|
||||
const authUserId = useAuthUserId();
|
||||
|
||||
|
||||
@@ -220,3 +220,11 @@ export interface MeResponse {
|
||||
export interface MatchesResponse {
|
||||
matches: ApiMatch[];
|
||||
}
|
||||
|
||||
export interface DdragonManifest {
|
||||
version: string;
|
||||
cdn: string;
|
||||
locale: string;
|
||||
champions: Record<string, string>;
|
||||
fetchedAt: string;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router';
|
||||
import { useAuction, useMatch, useMe } from '../api/hooks';
|
||||
import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks';
|
||||
import {
|
||||
formatTierLabel,
|
||||
getTierColorToken,
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
useDevCaptainSide,
|
||||
} from '../config';
|
||||
import { ApiError } from '../lib/api';
|
||||
import { championIconUrl, profileIconUrl } from '../lib/ddragon';
|
||||
import { positionIcon, positionLabel } from '../lib/league';
|
||||
import type { Position } from '../api/types';
|
||||
|
||||
@@ -53,6 +54,7 @@ function TeamPanel({
|
||||
isActive: boolean;
|
||||
isLeft: boolean;
|
||||
}) {
|
||||
const { data: ddragon } = useDdragonManifest();
|
||||
const borderColor =
|
||||
team.side === 'blue' ? 'border-blue-500/25' : 'border-red-500/25';
|
||||
const accentBar = team.side === 'blue' ? 'bg-blue-500' : 'bg-red-500';
|
||||
@@ -92,7 +94,7 @@ function TeamPanel({
|
||||
<div key={`${member.userId}-${member.assignedPosition}`} className="px-3 py-1.5 flex items-center gap-2">
|
||||
<div className="w-6 h-6 bg-base-content/10 overflow-hidden shrink-0">
|
||||
<img
|
||||
src={`https://ddragon.leagueoflegends.com/cdn/16.7.1/img/profileicon/${member.profileIconId}.png`}
|
||||
src={profileIconUrl(ddragon, member.profileIconId)}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
@@ -130,6 +132,7 @@ function PlayerSpotlight({
|
||||
}: {
|
||||
state: AuctionStateView;
|
||||
}) {
|
||||
const { data: ddragon } = useDdragonManifest();
|
||||
const player = state.currentPlayer;
|
||||
if (!player) return null;
|
||||
|
||||
@@ -151,7 +154,7 @@ function PlayerSpotlight({
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-16 h-16 bg-base-content/10 overflow-hidden shrink-0">
|
||||
<img
|
||||
src={`https://ddragon.leagueoflegends.com/cdn/16.7.1/img/profileicon/${player.profileIconId}.png`}
|
||||
src={profileIconUrl(ddragon, player.profileIconId)}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
@@ -190,15 +193,19 @@ function PlayerSpotlight({
|
||||
</h4>
|
||||
<div className="space-y-2">
|
||||
{player.masteries.length > 0 ? (
|
||||
player.masteries.map((mastery) => (
|
||||
player.masteries.map((mastery) => {
|
||||
const iconUrl = championIconUrl(ddragon, mastery.championId);
|
||||
return (
|
||||
<div key={mastery.championId} className="flex items-center gap-2">
|
||||
<div className="w-7 h-7 bg-base-content/10 overflow-hidden shrink-0">
|
||||
<img
|
||||
src={`https://ddragon.leagueoflegends.com/cdn/16.7.1/img/champion/${mastery.championId}.png`}
|
||||
alt={mastery.championName}
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
{iconUrl ? (
|
||||
<img
|
||||
src={iconUrl}
|
||||
alt={mastery.championName}
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-[12px] font-medium text-base-content truncate">
|
||||
@@ -209,7 +216,8 @@ function PlayerSpotlight({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<div className="text-[11px] text-base-content/25">
|
||||
숙련도 데이터가 없습니다.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import { useAuction, useMatch, useMe } from '../api/hooks';
|
||||
import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks';
|
||||
import {
|
||||
buildDefaultPreferredPositions,
|
||||
formatTierLabel,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from '../api/mappers';
|
||||
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config';
|
||||
import { apiFetch, ApiError } from '../lib/api';
|
||||
import { profileIconUrl } from '../lib/ddragon';
|
||||
import { positionIcon, positionLabel } from '../lib/league';
|
||||
import type { Position } from '../api/types';
|
||||
|
||||
@@ -92,6 +93,7 @@ function ParticipantRow({
|
||||
index: number;
|
||||
assignedPos?: Position;
|
||||
}) {
|
||||
const { data: ddragon } = useDdragonManifest();
|
||||
return (
|
||||
<tr className="border-b border-base-content/5 last:border-b-0 hover:bg-base-content/[0.02] transition-colors">
|
||||
<td className="py-2 px-3 text-center text-[11px] text-base-content/30 w-8">
|
||||
@@ -101,7 +103,7 @@ function ParticipantRow({
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-7 h-7 bg-base-content/10 overflow-hidden shrink-0">
|
||||
<img
|
||||
src={`https://ddragon.leagueoflegends.com/cdn/16.7.1/img/profileicon/${participant.profileIconId}.png`}
|
||||
src={profileIconUrl(ddragon, participant.profileIconId)}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
|
||||
Reference in new issue
Block a user