Docs / Guides
Build a collection app
People like to keep track of the games they own and show their shelf to friends. This guide builds that app on the API, start to finish: a command-line program in one file, Node 24, no packages. The calls are the same ones a web or phone app would make, so swap the terminal for your own interface when you are done.
It covers the parts every collection app runs into:
- Importing an existing collection from a BoardGameGeek export, with a question for the games it is not sure about.
- Adding games by typing part of a name, typos and other titles included.
- Showing the shelf with expansions under their games.
- Keeping up when the catalog changes: two entries merged into one, one deleted.
- Game night: what can five of us play in an hour, from both our shelves?
Get the whole file, and a sample export to try it on:
curl -O https://tablearchive.dev/examples/shelf.mjs
curl -O https://tablearchive.dev/examples/collection.csv
export TA_KEY=bgdb_… # from Account → API keys
node shelf.mjs import collection.csv
node shelf.mjs showSetup
The shelf lives in shelf.json: each game's ID with its name (for showing it without asking the API) and a cursor in the change feed. Store IDs, never slugs: a slug changes when a game is renamed, an ID does not.
const BASE = process.env.TA_URL ?? 'https://tablearchive.dev'
const KEY = process.env.TA_KEY
const FILE = process.env.SHELF ?? 'shelf.json'
// One request, waiting out the rate limit when it says to.
async function api(path, body) {
for (;;) {
const res = await fetch(BASE + path, {
method: body ? 'POST' : 'GET',
headers: { ...(KEY && { Authorization: `Bearer ${KEY}` }), ...(body && { 'Content-Type': 'application/json' }) },
body: body && JSON.stringify(body),
})
if (res.status === 429) {
const seconds = Number(res.headers.get('retry-after') ?? 5)
console.log(`Rate limited, waiting ${seconds} s`)
await new Promise((resolve) => setTimeout(resolve, seconds * 1000))
continue
}
// A proxy's error page is not JSON; keep the status either way.
const data = res.headers.get('content-type')?.includes('json') ? await res.json() : null
if (!res.ok) throw new Error(`${res.status}: ${data?.error ?? res.statusText}`)
return data
}
}
// The shelf: the games' IDs (with their names, for showing offline) and where we are in the change feed.
const load = () => (fs.existsSync(FILE) ? JSON.parse(fs.readFileSync(FILE, 'utf8')) : { games: {}, cursor: null })
const save = (shelf) => fs.writeFileSync(FILE, `${JSON.stringify(shelf, null, 2)}\n`)
const chunks = (list, size) => Array.from({ length: Math.ceil(list.length / size) }, (_, i) => list.slice(i * size, (i + 1) * size))
// Follow changes from now on: the newest event is where the shelf's feed starts.
async function startFollowing(shelf) {
shelf.cursor ??= Number((await api('/v1/events?limit=1')).events[0]?.id ?? 0)
}
let prompt
const ask = (question) => (prompt ??= createInterface({ input: process.stdin, output: process.stdout })).question(question)api() makes one request and, when the rate limit answers 429, waits as long as Retry-After says and tries again. Every call below goes through it.
1. Import a BoardGameGeek collection
BoardGameGeek exports a collection as CSV, with a row per game and columns including objectid (its BGG ID), objectname, yearpublished, and own. A small parser, since names have commas and quotes in them:
function parseCsv(text) {
const rows = [[]]
let field = ''
let quoted = false
for (let i = 0; i < text.length; i++) {
const c = text[i]
if (quoted) {
if (c === '"' && text[i + 1] === '"') field += text[++i]
else if (c === '"') quoted = false
else field += c
} else if (c === '"') quoted = true
else if (c === ',') rows.at(-1).push(field), (field = '')
else if (c === '\n') rows.at(-1).push(field.replace(/\r$/, '')), (field = ''), rows.push([])
else field += c
}
if (field) rows.at(-1).push(field)
return rows.filter((row) => row.length > 1)
}Then POST /v1/items/resolve, 200 games at a time. Every game goes in by its BoardGameGeek ID first. Rows without one, and BGG IDs the catalog does not know yet, go round again by name and year. Each answer has a confidence:
exactandlikelygo straight on the shelf.possiblemeans several games fit about as well (three games called Mutant), so the app asks, offeringmatchandcandidates.- No
matchat all: not in the catalog yet.
async function importBgg(file) {
// A spreadsheet may have saved it with a byte-order mark in front.
const [header, ...rows] = parseCsv(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
const col = (name) => header.indexOf(name)
const owned = rows
.filter((row) => row[col('own')] === '1')
.map((row) => ({ bgg: row[col('objectid')]?.trim(), name: row[col('objectname')]?.trim(), year: Number(row[col('yearpublished')]) || undefined }))
const shelf = load()
await startFollowing(shelf)
let added = 0
const put = (item) => (added += item.id in shelf.games ? 0 : 1, (shelf.games[item.id] = item.name))
const unsure = []
const notFound = []
const resolve = async (games, entry) => {
const missed = []
for (const batch of chunks(games, 200)) {
const { results } = await api('/v1/items/resolve', { entries: batch.map(entry) })
results.forEach(({ match, confidence, candidates }, i) => {
if (confidence === 'exact' || confidence === 'likely') put(match)
else if (match) unsure.push({ game: batch[i], options: [match, ...candidates] })
else missed.push(batch[i])
})
save(shelf) // after every batch, so a failure later keeps what is done
}
return missed
}
// By BoardGameGeek ID first; then by name and year, for rows without an ID and IDs we do not know.
const missed = await resolve(owned.filter((g) => g.bgg), (g) => ({ external_id: g.bgg, source: 'bgg' }))
const byName = [...owned.filter((g) => !g.bgg), ...missed].filter((g) => g.name)
notFound.push(...(await resolve(byName, (g) => ({ name: g.name, year: g.year }))))
for (const { game, options } of unsure) {
console.log(`\n"${game.name}" could be:`)
options.forEach((o, i) => console.log(` ${i + 1}. ${o.name}${o.year_published ? ` (${o.year_published})` : ''}`))
const pick = options[Number(await ask('Which one? (Enter to skip) ')) - 1]
if (pick) put(pick)
}
save(shelf)
for (const game of notFound) console.log(`Not in the catalog: ${game.name}`)
console.log(`Added ${added} of ${owned.length} games.`)
}A few things to notice. The shelf is saved after every batch, so a failure halfway through a big collection keeps what was done. Resolve has a budget of its own, 20 calls a minute, which is 4,000 games a minute: plenty, and api() waits if a huge collection hits it. And startFollowing() (in the setup above) sets the cursor to the newest event, so step 4 follows changes from the moment the shelf began.
2. Add a game by typing
GET /v1/items/suggest answers with names that start with what was typed, then names that contain it, then near misses, so "terraformng" still finds Terraforming Mars. matched_name says when an alternate title matched ("also known as Die Siedler von Catan"); show it, or people wonder why the result is there.
async function addByName(...words) {
const query = new URLSearchParams({ q: words.join(' '), limit: '5' })
const { items } = await api(`/v1/items/suggest?${query}`)
if (!items.length) return console.log('Nothing by that name.')
items.forEach((it, i) =>
console.log(` ${i + 1}. ${it.name}${it.year_published ? ` (${it.year_published})` : ''}${it.matched_name ? `, also known as ${it.matched_name}` : ''}`),
)
const pick = items[Number(await ask('Which one? ')) - 1]
if (!pick) return
const shelf = load()
shelf.games[pick.id] = pick.name
await startFollowing(shelf)
save(shelf)
console.log(`Added ${pick.name}.`)
}In an app with a search box, call it on each pause in typing (150 to 250 ms), not on every key: each call counts against the rate limit.
3. Show the shelf
GET /v1/items?ids= fetches up to 200 games in one request, in the order asked. Each has a parent: the game an expansion, edition, or accessory belongs to, or null for a game itself. Grouping by parent.id puts expansions under their games, even when the base game is not on the shelf.
async function show() {
const shelf = load()
const items = []
for (const batch of chunks(Object.keys(shelf.games), 200)) {
const page = await api(`/v1/items?ids=${batch.join(',')}`)
items.push(...page.items)
// IDs that changed (two entries merged into one) or went away.
for (const old of [...Object.keys(page.moved), ...page.missing]) delete shelf.games[old]
}
for (const item of items) shelf.games[item.id] = item.name
save(shelf)
const groups = new Map()
for (const item of items) {
const key = item.parent?.id ?? item.id
const group = groups.get(key) ?? { name: item.parent?.name ?? item.name, owned: false, parts: [] }
if (item.parent) group.parts.push(item)
// An edition of the game is a copy of it to play.
if (!item.parent || item.parent.relation === 'edition_of') group.owned = true
groups.set(key, group)
}
for (const group of [...groups.values()].sort((a, b) => a.name.localeCompare(b.name))) {
console.log(group.owned ? group.name : `${group.name} (not on the shelf)`)
for (const part of group.parts) console.log(` + ${part.name} (${part.parent.relation.replace(/_.*/, '')})`)
}
}The answer also says which IDs no longer exist as asked: moved (two entries were the same game and were merged; the survivor is in items) and missing (deleted). The app drops the old IDs and keeps what came back, so the shelf heals itself every time it is shown.
With the sample export:
Carcassonne
Cascadia
Dominion
+ Dominion: Prosperity (expansion)
+ Dominion: Alchemy (expansion)
Pandemic
WingspanAn edition counts as owning the game, so a shelf with only Dominion (Second Edition) shows Dominion as owned, with the edition under it.
4. Stay in sync
Showing the shelf fixes it as it goes, but an app that keeps its own copy (names, photos, player counts for filtering) wants to hear about changes as they happen. POST /v1/events/search is the change feed for just the games named, up to 5,000:
async function sync() {
const shelf = load()
// One feed covers up to 5,000 games; a bigger collection follows its games in groups, each with its own cursor.
if (Object.keys(shelf.games).length > 5000) throw new Error('More than 5,000 games: split the shelf to follow them')
await startFollowing(shelf)
for (;;) {
const { events } = await api('/v1/events/search', { items: Object.keys(shelf.games), after: shelf.cursor ?? 0, limit: 200 })
if (!events.length) break
for (const event of events) {
if (event.type === 'merged' && event.changes.merged.id in shelf.games) {
delete shelf.games[event.changes.merged.id]
shelf.games[event.item_id] = event.item_name
console.log(`${event.changes.merged.name} is now ${event.item_name}`)
} else if (event.type === 'deleted' && event.item_id in shelf.games) {
console.log(`${shelf.games[event.item_id]} was removed from the catalog`)
delete shelf.games[event.item_id]
} else if (event.item_name && event.item_id in shelf.games) {
shelf.games[event.item_id] = event.item_name
}
// The last event processed, not the highest number seen.
shelf.cursor = Number(event.id)
}
save(shelf)
}
console.log('Up to date.')
}merged: the event belongs to the survivor, andchanges.mergednames the ID that went away. Move whatever you stored toitem_id.deleted: the game is gone from the catalog, history and all; the event carries only its ID.- Anything else (
updated,photo_added, ...): fetch the game again if you keep more than its name.
One feed follows up to 5,000 games; past that, follow the collection in groups with a cursor each. Store the id of the last event you processed as the cursor, not the largest number you have seen. The feed runs in the order changes were written, and ids are not always rising; in exchange, nothing ever turns up behind your cursor. Run sync on a timer, or when the app opens.
5. Game night
Put two shelves together and ask POST /v1/items/search, which takes the filters of GET /v1/items in a body with up to 2,000 IDs:
async function tonight(players, ...rest) {
if (!(Number(players) > 0)) return console.log('How many players? node shelf.mjs tonight 5 [minutes] [friend.json]')
const minutes = rest.find((arg) => /^\d+$/.test(arg))
const ids = new Set(Object.keys(load().games))
for (const file of rest.filter((arg) => arg.endsWith('.json'))) for (const id of Object.keys(JSON.parse(fs.readFileSync(file, 'utf8')).games)) ids.add(id)
// Up to 2,000 IDs a request, 200 games a page.
const items = []
for (const batch of chunks([...ids], 2000)) {
for (let offset = 0; ; offset += 200) {
const page = await api('/v1/items/search', {
ids: batch,
players: Number(players),
...(minutes && { max_playtime: Number(minutes) }),
sort: 'popular',
limit: 200,
offset,
})
items.push(...page.items)
if (offset + 200 >= page.total) break
}
}
if (!items.length) return console.log('Nothing fits. Maybe a longer evening?')
for (const { name, data } of items) {
const shortest = data.min_playtime ?? data.max_playtime
const minutes = data.max_playtime ? `, ${shortest === data.max_playtime ? '' : `${shortest}–`}${data.max_playtime} min` : ''
console.log(`${name} ${data.min_players}–${data.max_players ?? data.min_players} players${minutes}`)
}
}node shelf.mjs tonight 5 60 friend.jsonplayers means playable with exactly that many; max_playtime keeps games that finish within it. Add age when the kids are playing. A page holds up to 200 games, so tonight pages with offset until it has them all.
Where to go from here
- Photos: each item in a list has
image(the box front, withthumb_urlandmedium_url). The links are signed and expire after a few hours, so fetch them when showing the shelf rather than storing them. - More about each game:
GET /v1/items/{idOrSlug}has credits, mechanics, editions, and where each fact came from. - A game we are missing: send it with
POST /v1/submissions. It is reviewed, then it is everyone's.