/** * Cliente RAWG * - `searchGames(query)` * - `getGameById(id)` */ import { fetch } from 'undici'; import type { MetadataGame, RawgGameResponse, RawgSearchResponse, PlatformInfo } from '../types'; export type { MetadataGame }; const API_BASE = 'https://api.rawg.io/api'; export async function searchGames(query: string): Promise { const key = process.env.RAWG_API_KEY; if (!key) return []; try { const url = `${API_BASE}/games?key=${encodeURIComponent(key)}&search=${encodeURIComponent( query )}&page_size=10`; const res = await fetch(url); if (!res.ok) return []; const json: RawgSearchResponse = (await res.json()) as RawgSearchResponse; const hits: RawgGameResponse[] = Array.isArray(json.results) ? json.results : []; return hits.map((r) => { const platforms: PlatformInfo[] | undefined = Array.isArray(r.platforms) ? r.platforms.map((p) => ({ id: p.id, name: p.name, slug: p.name?.toLowerCase().replace(/\s+/g, '-'), })) : undefined; const genres: string[] | undefined = Array.isArray(r.genres) ? r.genres.map((g) => g.name) : undefined; return { id: r.id, name: r.name, slug: r.slug, releaseDate: r.released, genres, platforms, coverUrl: r.background_image ?? undefined, source: 'rawg', }; }); } catch (err) { // eslint-disable-next-line no-console console.debug('rawgClient.searchGames error', err); return []; } } export async function getGameById(id: number): Promise { const key = process.env.RAWG_API_KEY; if (!key) return null; try { const url = `${API_BASE}/games/${encodeURIComponent(String(id))}?key=${encodeURIComponent( key )}`; const res = await fetch(url); if (!res.ok) return null; const json: RawgGameResponse = (await res.json()) as RawgGameResponse; if (!json) return null; const platforms: PlatformInfo[] | undefined = Array.isArray(json.platforms) ? json.platforms.map((p) => ({ id: p.id, name: p.name, slug: p.name?.toLowerCase().replace(/\s+/g, '-'), })) : undefined; const genres: string[] | undefined = Array.isArray(json.genres) ? json.genres.map((g) => g.name) : undefined; return { id: json.id, name: json.name, slug: json.slug, releaseDate: json.released, genres, platforms, coverUrl: json.background_image ?? undefined, source: 'rawg', }; } catch (err) { // eslint-disable-next-line no-console console.debug('rawgClient.getGameById error', err); return null; } } /** * Metadatos: * Autor: GitHub Copilot * Última actualización: 2026-02-11 */