From 6415200f3477821150c21ceed38dca89e6b66d84 Mon Sep 17 00:00:00 2001 From: Adrian Bonpin Date: Sat, 25 Apr 2026 21:37:34 +0800 Subject: [PATCH] feat: add steam game search --- app/api/[[...slugs]]/route.ts | 9 + app/game/[id]/game-page-client.tsx | 360 +++++++++++++++++++++++++++++ app/game/[id]/page.tsx | 188 +++++++++++++++ app/search/page.tsx | 198 +++++++++++++++- components/navbar.tsx | 33 +-- lib/api/game-stub.ts | 90 ++++++++ lib/api/search-unified.ts | 166 +++++++++++++ lib/api/steam-search.ts | 62 +++++ lib/hooks/useDebounce.ts | 12 + lib/steam/sync.ts | 72 ++++++ next.config.ts | 16 ++ 11 files changed, 1188 insertions(+), 18 deletions(-) create mode 100644 app/game/[id]/game-page-client.tsx create mode 100644 app/game/[id]/page.tsx create mode 100644 lib/api/game-stub.ts create mode 100644 lib/api/search-unified.ts create mode 100644 lib/api/steam-search.ts create mode 100644 lib/hooks/useDebounce.ts create mode 100644 lib/steam/sync.ts diff --git a/app/api/[[...slugs]]/route.ts b/app/api/[[...slugs]]/route.ts index 5e6989c..7b378e5 100644 --- a/app/api/[[...slugs]]/route.ts +++ b/app/api/[[...slugs]]/route.ts @@ -14,6 +14,9 @@ import { presetSettingsRoutes, commentsRoutes, } from "@/lib/api" +import { steamSearchRoutes } from "@/lib/api/steam-search" +import { searchUnifiedRoutes } from "@/lib/api/search-unified" +import { gameStubRoutes } from "@/lib/api/game-stub" const betterAuth = new Elysia({ name: "better-auth" }) .mount(auth.handler) @@ -65,6 +68,12 @@ export const app = new Elysia({ prefix: "/api" }) .use(presetSettingsRoutes) // Comments .use(commentsRoutes) + // Steam search proxy + .use(steamSearchRoutes) + // Unified search + .use(searchUnifiedRoutes) + // Game stub creation + .use(gameStubRoutes) // Root .get("/", () => ({ name: "DeckyVault API", diff --git a/app/game/[id]/game-page-client.tsx b/app/game/[id]/game-page-client.tsx new file mode 100644 index 0000000..7609aaf --- /dev/null +++ b/app/game/[id]/game-page-client.tsx @@ -0,0 +1,360 @@ +"use client" + +import { useState } from "react" +import Image from "next/image" +import { + Gamepad2Icon, + MessageSquareIcon, + SettingsIcon, + TrendingUpIcon, + ExternalLinkIcon, + ClockIcon, +} from "lucide-react" + +interface Game { + id: string + steamAppId: number | null + title: string + description: string | null + developer: string | null + publisher: string | null + genres: string[] | null + headerImage: string | null + capsuleImage: string | null + storeUrl: string | null + source: string + lastSync: string | null + syncStatus: string | null + createdAt: string +} + +interface Counts { + benchmarks: number + presets: number + comments: number +} + +interface PlatformSupport { + id: string + gameId: string + hardwareSlug: string + isSupported: boolean + protonStatus: string +} + +const TABS = [ + { key: "overview", label: "Overview", icon: Gamepad2Icon }, + { key: "benchmarks", label: "Benchmarks", icon: TrendingUpIcon }, + { key: "presets", label: "Presets", icon: SettingsIcon }, + { key: "comments", label: "Comments", icon: MessageSquareIcon }, +] as const + +type TabKey = (typeof TABS)[number]["key"] + +export function GamePageClient({ + game, + counts, + platformSupport, +}: { + game: Game + counts: Counts + platformSupport: PlatformSupport[] +}) { + const [activeTab, setActiveTab] = useState("overview") + + const headerImage = game.headerImage || game.capsuleImage + + return ( +
+ {/* Hero */} +
+ {headerImage ? ( + {game.title} + ) : ( +
+ +
+ )} +
+ +
+
+

+ {game.title} +

+
+ {game.developer && {game.developer}} + {game.developer && game.publisher && ( + + )} + {game.publisher && {game.publisher}} + {game.genres && game.genres.length > 0 && ( + <> + + + {game.genres.join(", ")} + + + )} +
+
+
+
+ + {/* Stats bar */} +
+
+ + + + {game.storeUrl && ( + + + Store + + )} +
+
+ + {/* Tabs */} +
+
+
+ {TABS.map((tab) => { + const Icon = tab.icon + const isActive = activeTab === tab.key + return ( + + ) + })} +
+ + {/* Tab content */} +
+ {activeTab === "overview" && ( + + )} + {activeTab === "benchmarks" && } + {activeTab === "presets" && } + {activeTab === "comments" && } +
+
+
+
+ ) +} + +function StatBadge({ + icon: Icon, + value, + label, +}: { + icon: React.ElementType + value: number + label: string +}) { + return ( +
+ + {value} + {label} +
+ ) +} + +function OverviewTab({ + game, + platformSupport, +}: { + game: Game + platformSupport: PlatformSupport[] +}) { + return ( +
+ {game.description && ( +
+

+ About +

+

+ {game.description} +

+
+ )} + + {/* Platform Support */} + {platformSupport.length > 0 && ( +
+

+ Platform Support +

+
+ {platformSupport.map((ps) => ( +
+ + {ps.hardwareSlug.replace(/-/g, " ")} + +
+ + {ps.isSupported ? "Supported" : "Unsupported"} + + + {ps.protonStatus} + +
+
+ ))} +
+
+ )} + + {/* Metadata */} +
+

+ Details +

+
+ + {game.steamAppId && ( + + )} + + {game.lastSync && ( + + )} +
+
+
+ ) +} + +function MetaItem({ + label, + value, + icon: Icon, +}: { + label: string + value: string + icon?: React.ElementType +}) { + return ( +
+ + {label} + + + {Icon && } + {value} + +
+ ) +} + +function formatDate(value: string | null): string { + if (!value) return "—" + return new Date(value).toLocaleDateString() +} + +function BenchmarksTab({ count }: { count: number }) { + if (count === 0) { + return ( +
+ +

No benchmarks yet

+
+ ) + } + return ( +
+ +

+ {count} benchmark{count !== 1 ? "s" : ""} — coming soon +

+
+ ) +} + +function PresetsTab({ count }: { count: number }) { + if (count === 0) { + return ( +
+ +

No presets yet

+
+ ) + } + return ( +
+ +

+ {count} preset{count !== 1 ? "s" : ""} — coming soon +

+
+ ) +} + +function CommentsTab({ count }: { count: number }) { + if (count === 0) { + return ( +
+ +

No comments yet

+
+ ) + } + return ( +
+ +

+ {count} comment{count !== 1 ? "s" : ""} — coming soon +

+
+ ) +} diff --git a/app/game/[id]/page.tsx b/app/game/[id]/page.tsx new file mode 100644 index 0000000..09b178b --- /dev/null +++ b/app/game/[id]/page.tsx @@ -0,0 +1,188 @@ +import { notFound } from "next/navigation" +import { after } from "next/server" +import { db } from "@/lib/db/index" +import { + games, + gameVersions, + performanceEntries, + communityPresets, + gameComments, + gamePlatformSupport, +} from "@/lib/db/schema" +import { eq, sql } from "drizzle-orm" +import { isSyncStale, syncSteamGame } from "@/lib/steam/sync" +import { GamePageClient } from "./game-page-client" + +export const metadata = { + title: "Game", +} + +async function createGameStub(steamAppId: number) { + const url = new URL("https://store.steampowered.com/api/appdetails/") + url.searchParams.set("appids", String(steamAppId)) + url.searchParams.set("cc", "US") + url.searchParams.set("l", "en") + + const res = await fetch(url.toString(), { + headers: { Accept: "application/json" }, + }) + + let title = `Steam App ${steamAppId}` + let developer: string | null = null + let publisher: string | null = null + let genres: string[] | null = null + let headerImage: string | null = null + let capsuleImage: string | null = null + let description: string | null = null + + if (res.ok) { + const data = (await res.json()) as Record< + string, + { success: boolean; data: { + name: string + developers?: string[] + publishers?: string[] + genres?: { description: string }[] + header_image?: string + capsule_imagev5?: string + short_description?: string + } } + > + const entry = data[String(steamAppId)] + if (entry?.success && entry.data) { + title = entry.data.name + developer = entry.data.developers?.[0] ?? null + publisher = entry.data.publishers?.[0] ?? null + genres = entry.data.genres?.map((g) => g.description) ?? [] + headerImage = entry.data.header_image ?? null + capsuleImage = entry.data.capsule_imagev5 ?? entry.data.header_image ?? null + description = entry.data.short_description ?? null + } + } + + const [game] = await db + .insert(games) + .values({ + steamAppId, + source: "steam", + title, + developer, + publisher, + genres, + headerImage, + capsuleImage, + description, + storeUrl: `https://store.steampowered.com/app/${steamAppId}`, + lastSync: new Date(), + syncStatus: "synced", + }) + .returning() + + return game +} + +export default async function GamePage({ + params, +}: { + params: Promise<{ id: string }> +}) { + const { id } = await params + const isNumeric = /^\d+$/.test(id) + + // ── Resolve game ──────────────────────────────────────────────── + let game + if (isNumeric) { + const rows = await db + .select() + .from(games) + .where(eq(games.steamAppId, Number(id))) + .limit(1) + game = rows[0] + } else { + const rows = await db + .select() + .from(games) + .where(eq(games.id, id)) + .limit(1) + game = rows[0] + } + + // Auto-create stub for missing Steam games + if (!game && isNumeric) { + try { + game = await createGameStub(Number(id)) + } catch (err) { + console.error("Failed to auto-create game stub:", err) + } + } + + if (!game) { + notFound() + } + + // ── Fetch related counts ──────────────────────────────────────── + const [benchmarkCount, presetCount, commentCount, platformSupport] = + await Promise.all([ + db + .select({ count: sql`count(*)::int` }) + .from(performanceEntries) + .innerJoin( + gameVersions, + eq(performanceEntries.versionId, gameVersions.id), + ) + .where(eq(gameVersions.gameId, game.id)) + .then((r) => r[0]?.count ?? 0), + db + .select({ count: sql`count(*)::int` }) + .from(communityPresets) + .where(eq(communityPresets.gameId, game.id)) + .then((r) => r[0]?.count ?? 0), + db + .select({ count: sql`count(*)::int` }) + .from(gameComments) + .where(eq(gameComments.gameId, game.id)) + .then((r) => r[0]?.count ?? 0), + db + .select() + .from(gamePlatformSupport) + .where(eq(gamePlatformSupport.gameId, game.id)) + .then((r) => r), + ]) + + // ── Stale-While-Revalidate: schedule background sync ──────────── + if (game.source === "steam" && game.steamAppId && isSyncStale(game.lastSync)) { + after(async () => { + await syncSteamGame(game.steamAppId!) + }) + } + + // Serialize for client component (Dates → strings) + const serializedGame = { + id: game.id, + steamAppId: game.steamAppId, + title: game.title, + description: game.description, + developer: game.developer, + publisher: game.publisher, + genres: game.genres, + headerImage: game.headerImage, + capsuleImage: game.capsuleImage, + storeUrl: game.storeUrl, + source: game.source, + lastSync: game.lastSync ? game.lastSync.toISOString() : null, + syncStatus: game.syncStatus, + createdAt: game.createdAt.toISOString(), + } + + return ( + + ) +} diff --git a/app/search/page.tsx b/app/search/page.tsx index c5069c0..92176dd 100644 --- a/app/search/page.tsx +++ b/app/search/page.tsx @@ -1,13 +1,71 @@ "use client" -import { Suspense } from "react" -import { useSearchParams } from "next/navigation" -import { Gamepad2Icon } from "lucide-react" +import { Suspense, useEffect, useState } from "react" +import { useRouter, useSearchParams } from "next/navigation" +import { ExternalLinkIcon, Gamepad2Icon, MessageSquareIcon, SettingsIcon, TrendingUpIcon } from "lucide-react" +import Image from "next/image" + +interface UnifiedResult { + kind: "local" | "steam" + id?: string + appId: number | null + title: string + image: string | null + developer: string | null + publisher: string | null + source: string + counts: { benchmarks: number; presets: number; comments: number } | null +} function SearchContent() { const searchParams = useSearchParams() + const router = useRouter() const query = searchParams.get("q") || "" + const [results, setResults] = useState([]) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + + useEffect(() => { + if (!query) { + setResults([]) + return + } + + let cancelled = false + + async function fetchResults() { + setLoading(true) + setError(null) + + try { + const res = await fetch( + `/api/search/unified?q=${encodeURIComponent(query)}`, + ) + if (!res.ok) throw new Error(await res.text()) + const data = await res.json() + if (!cancelled) setResults(data.results || []) + } catch (err) { + if (!cancelled) { + setError("Failed to fetch search results") + console.error(err) + } + } finally { + if (!cancelled) setLoading(false) + } + } + + fetchResults() + return () => { cancelled = true } + }, [query]) + + function handleClick(result: UnifiedResult) { + const path = result.appId + ? `/game/${result.appId}` + : `/game/${result.id}` + router.push(path) + } + return (
@@ -16,7 +74,7 @@ function SearchContent() {

{query - ? "Showing results from the database..." + ? `${results.length} result${results.length !== 1 ? "s" : ""} found` : "Enter a game name or AppID to find benchmarks, settings, and reviews."}

@@ -29,7 +87,7 @@ function SearchContent() {
)} - {query && ( + {query && loading && (

@@ -37,11 +95,141 @@ function SearchContent() {

)} + + {query && !loading && error && ( +
+

{error}

+
+ )} + + {query && !loading && !error && results.length === 0 && ( +
+ +

+ No results found for "{query}" +

+
+ )} + + {query && !loading && !error && results.length > 0 && ( +
+ {results.map((result, idx) => ( + + ))} +
+ )}
) } +function SearchResultCard({ + result, + onClick, +}: { + result: UnifiedResult + onClick: (r: UnifiedResult) => void +}) { + const isLocal = result.kind === "local" + const hasData = isLocal && result.counts && ( + result.counts.benchmarks > 0 || + result.counts.presets > 0 || + result.counts.comments > 0 + ) + const hasDeveloperInfo = result.developer || result.publisher + + return ( +
onClick(result)} + > + {/* Image */} +
+ {result.image ? ( + {result.title} + ) : ( +
+ +
+ )} + {/* Source badge */} +
+ {isLocal && ( + + In Database + + )} + {!isLocal && result.appId && ( + e.stopPropagation()} + > + Steam + + + )} +
+
+ + {/* Info */} +
+

+ {result.title} +

+ {hasDeveloperInfo ? ( +

+ {result.developer || result.publisher} +

+ ) : !isLocal && result.appId ? ( +

+ AppID: {result.appId} +

+ ) : null} +
+ + {/* Stats (local only) */} + {isLocal && result.counts && ( +
+ {result.counts.benchmarks > 0 && ( + + + {result.counts.benchmarks} + + )} + {result.counts.presets > 0 && ( + + + {result.counts.presets} + + )} + {result.counts.comments > 0 && ( + + + {result.counts.comments} + + )} + {!hasData && ( + No data yet + )} +
+ )} +
+ ) +} + export default function SearchPage() { return ( diff --git a/components/navbar.tsx b/components/navbar.tsx index 7704566..fc475d0 100644 --- a/components/navbar.tsx +++ b/components/navbar.tsx @@ -8,6 +8,7 @@ import { useEffect, useRef, useState } from "react" import { CircleXIcon, Gamepad2Icon, MenuIcon, XIcon } from "lucide-react" import { routes } from "@/lib/routes" import { usePathname, useRouter, useSearchParams } from "next/navigation" +import { useDebounce } from "@/lib/hooks/useDebounce" export default function Navbar() { const pathname = usePathname() @@ -17,6 +18,7 @@ export default function Navbar() { const isLanding = pathname === "/" const [searchQuery, setSearchQuery] = useState("") + const debouncedQuery = useDebounce(searchQuery, 300) const [mobileMenuOpen, setMobileMenuOpen] = useState(false) const [isFocused, setIsFocused] = useState(false) const [forceFocusStyles, setForceFocusStyles] = useState(false) @@ -24,10 +26,25 @@ export default function Navbar() { // Sync search query with URL ?q= param useEffect(() => { - const q = searchParams.get("q") - if (q) setSearchQuery(q) + const q = searchParams.get("q") || "" + setSearchQuery(q) }, [searchParams]) + // Update URL when debounced query changes (skip if already matches) + useEffect(() => { + if (isLanding) return + const currentQ = searchParams.get("q") || "" + if (debouncedQuery === currentQ) return + + const params = new URLSearchParams(searchParams.toString()) + if (debouncedQuery) { + params.set("q", debouncedQuery) + } else { + params.delete("q") + } + router.replace(`/search?${params.toString()}`, { scroll: false }) + }, [debouncedQuery, isLanding, router, searchParams]) + // Maintain focus & styles when flying from landing page search useEffect(() => { if ( @@ -47,17 +64,7 @@ export default function Navbar() { }, [isLanding, searchQuery]) const handleSearchChange = (e: React.ChangeEvent) => { - const value = e.target.value - setSearchQuery(value) - if (!isLanding) { - const params = new URLSearchParams(searchParams.toString()) - if (value) { - params.set("q", value) - } else { - params.delete("q") - } - router.replace(`/search?${params.toString()}`, { scroll: false }) - } + setSearchQuery(e.target.value) } const handleSearchSubmit = () => { diff --git a/lib/api/game-stub.ts b/lib/api/game-stub.ts new file mode 100644 index 0000000..d97a569 --- /dev/null +++ b/lib/api/game-stub.ts @@ -0,0 +1,90 @@ +import { Elysia, t } from "elysia" +import { db } from "@/lib/db/index" +import { games } from "@/lib/db/schema" +import { eq } from "drizzle-orm" + +interface SteamAppDetails { + steam_appid: number + name: string + developers?: string[] + publishers?: string[] + header_image?: string + capsule_imagev5?: string + genres?: { id: string; description: string }[] + website?: string +} + +export const gameStubRoutes = new Elysia({ prefix: "/games" }).post( + "/stub", + async ({ body, set }) => { + // Check if already exists + const [existing] = await db + .select() + .from(games) + .where(eq(games.steamAppId, body.steamAppId)) + .limit(1) + + if (existing) { + return { game: existing, created: false } + } + + // Fetch details from Steam + let details: SteamAppDetails | null = null + try { + const url = new URL("https://store.steampowered.com/api/appdetails/") + url.searchParams.set("appids", String(body.steamAppId)) + url.searchParams.set("cc", "US") + url.searchParams.set("l", "en") + + const res = await fetch(url.toString(), { + headers: { Accept: "application/json" }, + }) + + if (res.ok) { + const data = (await res.json()) as Record< + string, + { success: boolean; data: SteamAppDetails } + > + const entry = data[String(body.steamAppId)] + if (entry?.success) { + details = entry.data + } + } + } catch (err) { + console.error("Failed to fetch Steam appdetails:", err) + } + + const title = details?.name || `Steam App ${body.steamAppId}` + const developer = details?.developers?.[0] || null + const publisher = details?.publishers?.[0] || null + const genres = details?.genres?.map((g) => g.description) || [] + const headerImage = details?.header_image || null + const capsuleImage = + details?.capsule_imagev5 || details?.header_image || null + + const [game] = await db + .insert(games) + .values({ + steamAppId: body.steamAppId, + source: "steam", + title, + developer, + publisher, + genres, + headerImage, + capsuleImage, + storeUrl: `https://store.steampowered.com/app/${body.steamAppId}`, + lastSync: new Date(), + syncStatus: "synced", + }) + .returning() + + set.status = 201 + return { game, created: true } + }, + { + body: t.Object({ + steamAppId: t.Number(), + }), + }, +) diff --git a/lib/api/search-unified.ts b/lib/api/search-unified.ts new file mode 100644 index 0000000..c2c0564 --- /dev/null +++ b/lib/api/search-unified.ts @@ -0,0 +1,166 @@ +import { Elysia, t } from "elysia" +import { db } from "@/lib/db/index" +import { games, gameVersions, performanceEntries, communityPresets, gameComments } from "@/lib/db/schema" +import { ilike, or, sql, eq, inArray } from "drizzle-orm" + +interface SteamSearchItem { + id: number + name: string + tiny_image: string + metascore: string + platforms: { windows: boolean; mac: boolean; linux: boolean } +} + +interface SteamSearchResponse { + items: SteamSearchItem[] + total: number +} + +export const searchUnifiedRoutes = new Elysia({ prefix: "/search" }).get( + "/unified", + async ({ query, set }) => { + if (!query.q || query.q.length < 2) { + set.status = 400 + return { error: "Query must be at least 2 characters" } + } + + const term = `%${query.q}%` + + // ── 1. Search local database ──────────────────────────────────── + const localGames = await db + .select() + .from(games) + .where( + or( + ilike(games.title, term), + ilike(games.developer, term), + ilike(games.publisher, term), + ), + ) + .limit(20) + + const localGameIds = localGames.map((g) => g.id) + const localSteamAppIds = new Set( + localGames.map((g) => g.steamAppId).filter(Boolean), + ) + + // ── 2. Count related data for local games ─────────────────────── + let benchmarkCounts: { gameId: string; count: number }[] = [] + let presetCounts: { gameId: string; count: number }[] = [] + let commentCounts: { gameId: string; count: number }[] = [] + + if (localGameIds.length > 0) { + const [bCounts, pCounts, cCounts] = await Promise.all([ + db + .select({ + gameId: gameVersions.gameId, + count: sql`count(*)::int`, + }) + .from(performanceEntries) + .innerJoin( + gameVersions, + eq(performanceEntries.versionId, gameVersions.id), + ) + .where(inArray(gameVersions.gameId, localGameIds)) + .groupBy(gameVersions.gameId), + db + .select({ + gameId: communityPresets.gameId, + count: sql`count(*)::int`, + }) + .from(communityPresets) + .where(inArray(communityPresets.gameId, localGameIds)) + .groupBy(communityPresets.gameId), + db + .select({ + gameId: gameComments.gameId, + count: sql`count(*)::int`, + }) + .from(gameComments) + .where(inArray(gameComments.gameId, localGameIds)) + .groupBy(gameComments.gameId), + ]) + benchmarkCounts = bCounts + presetCounts = pCounts + commentCounts = cCounts + } + + const countMap = new Map< + string, + { benchmarks: number; presets: number; comments: number } + >() + for (const g of localGames) { + countMap.set(g.id, { benchmarks: 0, presets: 0, comments: 0 }) + } + for (const c of benchmarkCounts) { + countMap.get(c.gameId)!.benchmarks = c.count + } + for (const c of presetCounts) { + countMap.get(c.gameId)!.presets = c.count + } + for (const c of commentCounts) { + countMap.get(c.gameId)!.comments = c.count + } + + // ── 3. Search Steam ───────────────────────────────────────────── + let steamItems: SteamSearchItem[] = [] + try { + const url = new URL("https://store.steampowered.com/api/storesearch/") + url.searchParams.set("term", query.q) + url.searchParams.set("cc", "US") + url.searchParams.set("l", "en") + + const res = await fetch(url.toString(), { + headers: { Accept: "application/json" }, + }) + if (res.ok) { + const data = (await res.json()) as SteamSearchResponse + steamItems = data.items || [] + } + } catch { + // Steam search failure is non-fatal + } + + // ── 4. Build unified results ──────────────────────────────────── + // Local games first (they have data), then Steam-only results + const results = [] + + // Add local games + for (const g of localGames) { + const counts = countMap.get(g.id)! + results.push({ + kind: "local" as const, + id: g.id, + appId: g.steamAppId, + title: g.title, + image: g.capsuleImage || g.headerImage, + developer: g.developer, + publisher: g.publisher, + source: g.source, + counts, + }) + } + + // Add Steam-only games (deduplicated against local steamAppIds) + for (const item of steamItems) { + if (localSteamAppIds.has(item.id)) continue + results.push({ + kind: "steam" as const, + appId: item.id, + title: item.name, + image: item.tiny_image, + developer: null, + publisher: null, + source: "steam" as const, + counts: null, + }) + } + + return { results, total: results.length } + }, + { + query: t.Object({ + q: t.String(), + }), + }, +) diff --git a/lib/api/steam-search.ts b/lib/api/steam-search.ts new file mode 100644 index 0000000..35339f7 --- /dev/null +++ b/lib/api/steam-search.ts @@ -0,0 +1,62 @@ +import { Elysia, t } from "elysia" + +interface SteamSearchItem { + id: number + name: string + tiny_image: string + metascore: string + platforms: { + windows: boolean + mac: boolean + linux: boolean + } +} + +export const steamSearchRoutes = new Elysia({ prefix: "/search" }) + .get( + "/steam", + async ({ query, set }) => { + if (!query.q || query.q.length < 2) { + set.status = 400 + return { error: "Query must be at least 2 characters" } + } + + try { + const url = new URL("https://store.steampowered.com/api/storesearch/") + url.searchParams.set("term", query.q) + url.searchParams.set("cc", "US") + url.searchParams.set("l", "en") + + const res = await fetch(url.toString(), { + headers: { Accept: "application/json" }, + }) + + if (!res.ok) { + set.status = 502 + return { error: "Failed to fetch from Steam" } + } + + const data = await res.json() + + return { + items: (data.items || []).map((item: SteamSearchItem) => ({ + appId: item.id, + title: item.name, + image: item.tiny_image, + platforms: item.platforms, + metascore: item.metascore, + })), + total: data.total || 0, + } + } catch (err) { + console.error("Steam search error:", err) + set.status = 500 + return { error: "Internal server error" } + } + }, + { + query: t.Object({ + q: t.String(), + }), + }, + ) diff --git a/lib/hooks/useDebounce.ts b/lib/hooks/useDebounce.ts new file mode 100644 index 0000000..ea039d8 --- /dev/null +++ b/lib/hooks/useDebounce.ts @@ -0,0 +1,12 @@ +import { useState, useEffect } from "react" + +export function useDebounce(value: T, delay: number): T { + const [debouncedValue, setDebouncedValue] = useState(value) + + useEffect(() => { + const timer = setTimeout(() => setDebouncedValue(value), delay) + return () => clearTimeout(timer) + }, [value, delay]) + + return debouncedValue +} diff --git a/lib/steam/sync.ts b/lib/steam/sync.ts new file mode 100644 index 0000000..ee16bc1 --- /dev/null +++ b/lib/steam/sync.ts @@ -0,0 +1,72 @@ +import { db } from "@/lib/db/index" +import { games } from "@/lib/db/schema" +import { eq } from "drizzle-orm" + +interface SteamAppDetails { + steam_appid: number + name: string + developers?: string[] + publishers?: string[] + header_image?: string + capsule_imagev5?: string + genres?: { id: string; description: string }[] + website?: string + short_description?: string +} + +const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000 + +export function isSyncStale(lastSync: Date | null): boolean { + if (!lastSync) return true + return Date.now() - new Date(lastSync).getTime() > SEVEN_DAYS_MS +} + +export async function syncSteamGame(steamAppId: number): Promise { + try { + const url = new URL("https://store.steampowered.com/api/appdetails/") + url.searchParams.set("appids", String(steamAppId)) + url.searchParams.set("cc", "US") + url.searchParams.set("l", "en") + + const res = await fetch(url.toString(), { + headers: { Accept: "application/json" }, + }) + + if (!res.ok) { + console.error(`Steam sync failed for ${steamAppId}: ${res.status}`) + return + } + + const data = (await res.json()) as Record< + string, + { success: boolean; data: SteamAppDetails } + > + const entry = data[String(steamAppId)] + + if (!entry?.success || !entry.data) { + console.error(`Steam sync: no data for ${steamAppId}`) + return + } + + const d = entry.data + + await db + .update(games) + .set({ + title: d.name, + developer: d.developers?.[0] || null, + publisher: d.publishers?.[0] || null, + description: d.short_description || null, + genres: d.genres?.map((g) => g.description) || [], + headerImage: d.header_image || null, + capsuleImage: d.capsule_imagev5 || d.header_image || null, + storeUrl: `https://store.steampowered.com/app/${steamAppId}`, + lastSync: new Date(), + syncStatus: "synced", + updatedAt: new Date(), + }) + .where(eq(games.steamAppId, steamAppId)) + } catch (err) { + console.error(`Steam sync error for ${steamAppId}:`, err) + } +} diff --git a/next.config.ts b/next.config.ts index 0b95cc2..dc03687 100644 --- a/next.config.ts +++ b/next.config.ts @@ -3,6 +3,22 @@ import type { NextConfig } from "next"; const nextConfig: NextConfig = { // Elysia is Bun-native and must not be bundled by Next.js serverExternalPackages: ["elysia", "@elysiajs/eden"], + images: { + remotePatterns: [ + { + protocol: "https", + hostname: "cdn.akamai.steamstatic.com", + port: "", + pathname: "/steam/apps/**", + }, + { + protocol: "https", + hostname: "shared.akamai.steamstatic.com", + port: "", + pathname: "/store_item_assets/**", + }, + ], + }, }; export default nextConfig;