Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions api/games.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

const RAWG = 'https://api.rawg.io/api/'
const STEAM_STORE = 'https://store.steampowered.com/api/'
const IGDB = 'https://api.igdb.com/v4/'
const TWITCH_TOKEN = 'https://id.twitch.tv/oauth2/token'

/** GET-only allowlists; nothing else upstream is reachable through us. */
const ALLOWED = {
Expand All @@ -17,6 +19,57 @@ const ALLOWED = {
// is unreachable: it is the only keyless list of games with cover art we have.
steam: (path) =>
path === 'storesearch' || path === 'appdetails' || path === 'featuredcategories',
// IGDB is the second catalogue with both console games and cover art — the gap
// neither Steam nor any keyless source can fill. Only the games endpoint is opened.
igdb: (path) => path === 'games',
}

/**
* IGDB authenticates through Twitch: a client-credentials token, good for about 60
* days, that has to be fetched before the first query. It is cached in module scope,
* which on Vercel means per warm instance — a cold start pays one extra round trip,
* and nothing is stored anywhere it could leak.
*
* Refreshed a minute early so a token cannot expire between the check and the call.
*/
let igdbToken = null

async function igdbAccessToken(clientId, clientSecret) {
if (igdbToken && igdbToken.expiresAt > Date.now() + 60_000) return igdbToken.value
const url = new URL(TWITCH_TOKEN)
url.searchParams.set('client_id', clientId)
url.searchParams.set('client_secret', clientSecret)
url.searchParams.set('grant_type', 'client_credentials')
const res = await fetch(url, { method: 'POST' })
if (!res.ok) throw new Error(`twitch token ${res.status}`)
const data = await res.json()
igdbToken = {
value: data.access_token,
expiresAt: Date.now() + (Number(data.expires_in) || 3600) * 1000,
}
return igdbToken.value
}

/**
* IGDB speaks its own query language over POST with a plain-text body, unlike the two
* GET APIs beside it. The client still calls us with an ordinary GET; the query is
* assembled here so the shape of IGDB's protocol never reaches the browser.
*
* `search` and the discover orderings are the only two forms allowed. Anything the
* client sends is quoted into a string literal, so it cannot inject clauses.
*/
function igdbBody(query) {
const fields =
'fields name,cover.image_id,first_release_date,genres.name,platforms.name,' +
'total_rating,aggregated_rating,summary;'
const limit = Math.min(Math.max(Number(query.limit) || 20, 1), 50)
const term = String(query.search ?? '').slice(0, 100).replace(/["\\]/g, '')
if (term) return `search "${term}"; ${fields} limit ${limit};`
if (query.upcoming === '1') {
const now = Math.floor(Date.now() / 1000)
return `${fields} where first_release_date > ${now} & cover != null; sort first_release_date asc; limit ${limit};`
}
return `${fields} where total_rating_count > 20 & cover != null; sort total_rating desc; limit ${limit};`
}

function cacheFor(source, path) {
Expand Down Expand Up @@ -103,6 +156,40 @@ export default async function handler(req, res) {
return
}

if (source === 'igdb') {
const clientId = process.env.IGDB_CLIENT_ID
const clientSecret = process.env.IGDB_CLIENT_SECRET
// Same contract as RAWG: 503 means "this catalogue is not configured here", and
// the client moves on to the next source rather than treating it as an outage.
if (!clientId || !clientSecret) {
res.status(503).json({ error: 'IGDB credentials not configured' })
return
}
try {
const token = await igdbAccessToken(clientId, clientSecret)
const upstream = await fetch(IGDB + path, {
method: 'POST',
headers: {
'Client-ID': clientId,
Authorization: `Bearer ${token}`,
'Content-Type': 'text/plain',
'User-Agent': 'GamesTable/1.0 (+https://github.com/mrWD/games-table)',
},
body: igdbBody(req.query),
})
const body = await upstream.text()
res.status(upstream.status)
res.setHeader('Content-Type', 'application/json; charset=utf-8')
if (upstream.ok) res.setHeader('Cache-Control', cacheFor(source, path))
res.send(body)
} catch {
// A failed token exchange must not poison the next request with a stale token.
igdbToken = null
res.status(502).json({ error: 'igdb unreachable' })
}
return
}

try {
const upstream = await fetch(buildUpstream(source, path, req.query, key), {
headers: { 'User-Agent': 'GamesTable/1.0 (+https://github.com/mrWD/games-table)' },
Expand Down
59 changes: 57 additions & 2 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ let rawgDisabled = false
const REQUEST_TIMEOUT_MS = 8000

async function proxy<T>(
source: 'rawg' | 'steam',
source: 'rawg' | 'steam' | 'igdb',
path: string,
params: Record<string, string> = {},
): Promise<T | null> {
Expand Down Expand Up @@ -182,6 +182,15 @@ export async function searchGames(query: string): Promise<GameSummary[]> {
return viaRawg.results.map(mapRawg)
}

// IGDB before Steam, and the order is the whole point: it covers consoles, so
// "zelda" and "mario" still return Nintendo titles when RAWG cannot answer. Steam
// returns nothing for either (measured — see DATA-SOURCES).
const viaIgdb = await proxy<IgdbGame[]>('igdb', 'games', { search: term, limit: '20' })
if (viaIgdb?.length) {
stats.source('igdb')
return viaIgdb.map(mapIgdb)
}

// Steam only knows PC titles, so this is a narrower answer, not an equal one.
const viaSteam = await proxy<{ items?: SteamSearchItem[] }>('steam', 'storesearch', {
term,
Expand Down Expand Up @@ -232,6 +241,48 @@ export async function lookupGame(id: string): Promise<GameSummary | null> {
}

/** Explore shelves: popular now and what is coming next. */
/**
* IGDB — the second catalogue, and the only one besides RAWG that has both console
* games and cover art. Steam has neither for consoles; the keyless sources measured in
* DATA-SOURCES have the games but not the art, because cover art is copyrighted.
*
* Ids are prefixed `igdb:` so an entry saved from here stays distinguishable from the
* same game saved via RAWG or Steam.
*/
interface IgdbGame {
id: number
name?: string
cover?: { image_id?: string }
first_release_date?: number
genres?: { name: string }[]
platforms?: { name: string }[]
total_rating?: number
aggregated_rating?: number
summary?: string
}

function mapIgdb(g: IgdbGame): GameSummary {
return {
id: `igdb:${g.id}`,
title: g.name ?? '',
// t_cover_big is 264×374 — the size the cards actually render.
cover: g.cover?.image_id
? `https://images.igdb.com/igdb/image/upload/t_cover_big/${g.cover.image_id}.jpg`
: null,
released: g.first_release_date
? new Date(g.first_release_date * 1000).toISOString().slice(0, 10)
: null,
genres: (g.genres ?? []).map((x) => x.name).slice(0, 3),
platforms: (g.platforms ?? []).map((x) => x.name).slice(0, 6),
// IGDB's aggregated_rating is the critic score, which is what the badge means
// elsewhere in this app; total_rating mixes in user votes, so it is not the same
// number and is deliberately not shown as one.
metacritic: g.aggregated_rating ? Math.round(g.aggregated_rating) : null,
rating: g.total_rating ? Math.round(g.total_rating) / 20 : null,
description: g.summary,
}
}

interface SteamFeaturedItem {
id: number
name?: string
Expand Down Expand Up @@ -291,7 +342,7 @@ function mapFeatured(items: SteamFeaturedItem[] | undefined): GameSummary[] {
* equivalent: RAWG covers every platform, Steam only PC. The screen names its source
* rather than passing a narrower list off as the same thing.
*/
export type DiscoverSource = 'rawg' | 'steam'
export type DiscoverSource = 'rawg' | 'igdb' | 'steam'
export interface Discover {
games: GameSummary[]
source: DiscoverSource
Expand All @@ -303,6 +354,8 @@ export async function popularGames(): Promise<Discover> {
page_size: '12',
})
if (data?.results?.length) return { games: data.results.map(mapRawg), source: 'rawg' }
const viaIgdb = await proxy<IgdbGame[]>('igdb', 'games', { limit: '12' })
if (viaIgdb?.length) return { games: viaIgdb.map(mapIgdb), source: 'igdb' }
const featured = await steamFeatured()
return { games: mapFeatured(featured?.new_releases?.items), source: 'steam' }
}
Expand All @@ -316,6 +369,8 @@ export async function upcomingGames(): Promise<Discover> {
page_size: '12',
})
if (data?.results?.length) return { games: data.results.map(mapRawg), source: 'rawg' }
const viaIgdb = await proxy<IgdbGame[]>('igdb', 'games', { upcoming: '1', limit: '12' })
if (viaIgdb?.length) return { games: viaIgdb.map(mapIgdb), source: 'igdb' }
const featured = await steamFeatured()
return { games: mapFeatured(featured?.coming_soon?.items), source: 'steam' }
}
2 changes: 1 addition & 1 deletion src/store/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { persist } from 'zustand/middleware'
* data never leaves the device and is not part of the library backup.
*/

export type SourceName = 'rawg' | 'steam'
export type SourceName = 'rawg' | 'igdb' | 'steam'

/** Keeping ~13 weeks is enough for the activity strip without growing forever. */
const MAX_DAYS = 90
Expand Down
Loading