Docs / Guides

Track a game collection in Google Sheets

Plenty of game collections already live in a spreadsheet. This guide gives one a TableArchive menu: type a game's name in a row, and the year, player counts, playtime, age, and the game it belongs to fill in from the API. It is a short Apps Script inside the sheet, so there is no add-on to install and no server to run.

GameYearMin playersMax playersMinutesAgeBelongs toCheck
Wingspan2019159010
Pandemic200824458
Dominion: Prosperityexpansion of Dominion
1830Which one? ▾

Each name becomes a link to the game's page, and an ID column keeps the TableArchive ID, which is what the sheet trusts from then on. Names are for people; IDs stay put when a game is renamed.

Set it up

  1. Make a new spreadsheet, then open Extensions → Apps Script.
  2. Replace everything in Code.gs with the contents of games-sheet.js, and save.
  3. Reload the spreadsheet. A TableArchive menu shows up in the menu bar.
  4. Choose TableArchive → Fill in new games. The first time, it makes a Games sheet with a header row.
  5. Type a few game names in column A, under the header, and choose Fill in new games again.

The first run of the menu asks for permission to edit the spreadsheet and to "connect to an external service", which is tablearchive.dev. Google then warns that it has not verified the app. It is your own script, so choose Advanced, then go on to the project.

Already have a list somewhere else? Paste the names into column A, and the years into column B if you have them, then fill in new games. Columns to the right of the hidden Choices column are yours for anything else: where the game lives, who borrowed it, when you last played.

The API call

Apps Script fetches with UrlFetchApp, which waits for the answer, so the code reads top to bottom with no await.

const BASE = 'https://tablearchive.dev'
const SHEET = 'Games'
const HEADERS = ['Game', 'Year', 'Min players', 'Max players', 'Minutes', 'Age', 'Belongs to', 'Check', 'ID', 'Choices']
// Where things are in a row, counting from 0. Columns after Choices are yours.
const COL = { game: 0, year: 1, check: 7, id: 8, choices: 9 }
// One request, waiting out the rate limit when it says to.
function api(path, body) {
  const key = PropertiesService.getUserProperties().getProperty('TA_KEY')
  for (;;) {
    const res = UrlFetchApp.fetch(BASE + path, {
      method: body ? 'post' : 'get',
      contentType: 'application/json',
      ...(body && { payload: JSON.stringify(body) }),
      headers: key ? { Authorization: `Bearer ${key}` } : {},
      muteHttpExceptions: true,
    })
    const status = res.getResponseCode()
    const headers = res.getHeaders()
    if (status === 429) {
      Utilities.sleep(Number(headers['Retry-After'] ?? headers['retry-after'] ?? 5) * 1000)
      continue
    }
    // A proxy's error page is not JSON; keep the status either way.
    let data = null
    try {
      data = JSON.parse(res.getContentText())
    } catch {}
    if (status >= 400) throw new Error(`TableArchive answered ${status}: ${data?.error ?? 'no details'}`)
    return data
  }
}

muteHttpExceptions hands back error responses instead of throwing, so the script can read Retry-After on a 429 and sleep that long. Anything else that goes wrong shows up as a red error bar in the sheet with TableArchive's own message.

The rest of the plumbing is in the file too: onOpen adds the menu, gamesSheet() finds the Games sheet (or makes it), read() gets its rows as values, and chunks() cuts a list into batches.

Reading the catalog needs no key, but scripts run on Google's servers, and the rate limit for calls without a key (50 a minute) is per address. Every other Apps Script project shares those addresses, so a key is worth the minute it takes. Make one under Account → API keys, then choose TableArchive → Set API key:

function setKey() {
  const ui = SpreadsheetApp.getUi()
  const answer = ui.prompt('TableArchive API key', 'From Account → API keys on tablearchive.dev. Leave it empty to go without.', ui.ButtonSet.OK_CANCEL)
  if (answer.getSelectedButton() !== ui.Button.OK) return
  const key = answer.getResponseText().trim()
  if (key) PropertiesService.getUserProperties().setProperty('TA_KEY', key)
  else PropertiesService.getUserProperties().deleteProperty('TA_KEY')
}

User properties belong to you alone. Share the spreadsheet and the people you share it with can run the menu, each with their own key or none, and none of them can read yours. Never paste a key into a cell or into the code: anyone who can open the sheet can see both.

Looking up names

POST /v1/items/resolve takes up to 200 names at once, each with a year if there is one, and answers in the same order. Every answer has a confidence:

  • exact and likely are good enough to fill in.
  • possible means several games fit about as well, so the sheet asks (below).
  • No match at all: the game is not in the catalog yet.
// Looks up the names in the given rows, 200 to a request, and writes each batch as it comes.
function fill(games, table, rows) {
  for (const batch of chunks(rows, 200)) {
    const found = new Map()
    const entries = batch.map((i) => ({ name: name(table[i]).slice(0, 300), ...(Number(table[i][COL.year]) && { year: Number(table[i][COL.year]) }) }))
    const { results } = api('/v1/items/resolve', { entries })
    results.forEach(({ match, confidence, candidates }, n) => {
      const i = batch[n]
      if (confidence === 'exact' || confidence === 'likely') found.set(i, match.id)
      else if (match) offer(games, i, [match, ...candidates])
      else games.getRange(i + 2, COL.check + 1).setValue('Not in the catalog').clearDataValidations()
    })
    details(games, found)
  }
}

name() reads the cell as trimmed text, since Sheets turns a name like 1830 into a number. Each batch is written as soon as it comes back, so if a later one fails, the rows before it keep their games. Fill in new games sends every row that has a name and no ID yet:

function fillNew() {
  const games = gamesSheet()
  const table = read(games)
  const rows = table.map((row, i) => i).filter((i) => name(table[i]) && table[i][COL.id] === '')
  fill(games, table, rows)
  SpreadsheetApp.getActive().toast(rows.length ? `Looked up ${rows.length} games.` : 'Nothing new to look up.')
}

Rows marked Not in the catalog go round again each time, so they fill in once someone adds the game. Resolve has a budget of 20 calls a minute on top of the usual limit, which is 4,000 names a minute; a big paste stays well under it.

Filling in a row

A match from resolve has a name and a year. The rest comes from GET /v1/items?ids=, up to 200 games a request:

// Fetches the items behind a Map of row → ID, 200 at a time, and writes each row.
function details(games, rows) {
  const items = {}
  for (const batch of chunks([...new Set(rows.values())], 200)) {
    const page = api(`/v1/items?ids=${batch.join(',')}`)
    for (const item of page.items) items[item.id] = item
    // Two entries turned out to be the same game: the old ID now means the survivor.
    for (const [old, now] of Object.entries(page.moved)) items[old] = items[now]
  }
  for (const [i, id] of rows) {
    if (items[id]) put(games, i, items[id])
    else games.getRange(i + 2, COL.check + 1).setValue('Gone from the catalog')
  }
}
// Writes a catalog item over row i: its name (linked to its page), the facts, and its ID.
function put(games, i, item) {
  const d = item.data
  const link = SpreadsheetApp.newRichTextValue().setText(item.name).setLinkUrl(`${BASE}/items/${item.id}`).build()
  games.getRange(i + 2, COL.game + 1).setRichTextValue(link)
  games.getRange(i + 2, COL.year + 1, 1, HEADERS.length - 1).setValues([[
    d.year_published ?? '',
    d.min_players ?? '',
    d.max_players ?? d.min_players ?? '',
    d.max_playtime ?? d.min_playtime ?? '',
    d.min_age ?? '',
    item.parent ? `${item.parent.relation.replace(/_/g, ' ')} ${item.parent.name}` : '',
    '',
    item.id,
    '',
  ]])
  games.getRange(i + 2, COL.check + 1).clearDataValidations()
}

The name in column A is replaced with the catalog's, so "wingspan" becomes Wingspan, and you can see at a glance what it matched. Fields the catalog does not have stay empty. A game that plays at one count has no max_players, so the row repeats min_players there, which keeps the game night formula below simple. parent is the game an expansion, edition, or accessory belongs to, and relation says which: expansion_of, edition_of, and so on.

Which one?

A short name like 1830 fits several games. When resolve is unsure, the Check cell gets a dropdown of the candidates, each with its year and kind, and their IDs go into the hidden Choices column in the same order:

// Several games fit about as well: a dropdown in Check to pick one, with their IDs kept in the hidden Choices column.
function offer(games, i, options) {
  const labels = options.map((o, n) => `${n + 1}. ${o.name} (${[o.year_published, o.kind.replace(/_/g, ' ')].filter(Boolean).join(' ')})`)
  const rule = SpreadsheetApp.newDataValidation().requireValueInList(labels).setAllowInvalid(true).build()
  games.getRange(i + 2, COL.check + 1).setValue('Which one?').setDataValidation(rule)
  games.getRange(i + 2, COL.choices + 1).setValue(options.map((o) => o.id).join(' '))
}

Picking one fills in the row, once the sheet fills in as you type (next section). Without that, type a fuller name, or add the year in column B, and fill in new games again.

Fill in as you type

A plain onEdit function runs without permission to reach the internet, so it cannot call the API. An installed trigger runs with the permissions you granted. TableArchive → Fill in as I type installs one, once:

// Calling a web address needs permission, which a plain onEdit does not have; an installed trigger does.
function fillAsIType() {
  const book = SpreadsheetApp.getActive()
  if (!ScriptApp.getProjectTriggers().some((t) => t.getHandlerFunction() === 'edited')) {
    ScriptApp.newTrigger('edited').forSpreadsheet(book).onEdit().create()
  }
  book.toast('Games now fill in as you type their names.')
}

From then on, every edit to the Games sheet calls edited. It cares about two columns:

function edited(e) {
  const games = e.range.getSheet()
  if (games.getName() !== SHEET) return
  const first = Math.max(e.range.getRow(), 2) - 2
  const last = e.range.getLastRow() - 2
  if (last < first) return

  // New names: clear what was there (keeping any columns pasted with them) and look them up.
  // Whole rows pasted with their IDs are games moving around the sheet; leave them be.
  if (e.range.getColumn() === COL.game + 1 && e.range.getLastColumn() <= COL.id) {
    const from = e.range.getLastColumn() + 1
    if (from <= HEADERS.length) games.getRange(first + 2, from, last - first + 1, HEADERS.length - from + 1).clearContent().clearDataValidations()
    const table = read(games)
    const rows = Array.from({ length: last - first + 1 }, (_, n) => first + n).filter((i) => table[i] && name(table[i]))
    fill(games, table, rows)
  }

  // A pick from the Which one? dropdown.
  if (e.range.getColumn() === COL.check + 1 && e.range.getNumRows() === 1 && e.range.getNumColumns() === 1) {
    const labels = e.range.getDataValidation()?.getCriteriaValues()[0] ?? []
    const id = String(games.getRange(first + 2, COL.choices + 1).getValue()).split(' ')[labels.indexOf(e.value)]
    if (id) details(games, new Map([[first, id]]))
  }
}
  • A new name in column A clears the old game's details from the row and looks the name up. Paste a block of names and years and it looks them all up in one request, keeping the years you pasted. Whole rows pasted with their IDs are games moving around the sheet, and stay as they are.
  • A pick in Check finds the label's place in the dropdown and takes the ID at the same place in Choices.

Changes the script makes do not fire the trigger, so writing a row never sets off another lookup. The trigger runs as you, for anyone editing the sheet, so the lookups count against your key. One person installs it; a second one from a collaborator would look every name up twice. To stop it, delete the trigger under Triggers (the clock icon) in the Apps Script editor.

Keeping it current

Games get new facts, renames, and now and then a merge, when two entries turn out to be the same game. Refresh every game fetches every row with an ID again:

// Names, facts, and IDs change now and then: fetch every game again.
function refreshAll() {
  const games = gamesSheet()
  const rows = new Map()
  read(games).forEach((row, i) => ID.test(row[COL.id]) && rows.set(i, row[COL.id].toLowerCase()))
  details(games, rows)
  SpreadsheetApp.getActive().toast(`Refreshed ${rows.size} games.`)
}

Only IDs that look like IDs go out, so a stray note in the ID column does not sink the whole request. details() handles the odd cases. A merged-away ID comes back in moved with the ID it became, and the row is written with the survivor's ID. An ID in missing was deleted, and the row says Gone from the catalog and keeps what it had. A thousand games is five requests.

To refresh on a schedule, add a time-driven trigger for refreshAll under Triggers in the Apps Script editor; once a week is plenty. Code that keeps its own copy of more than a sheet's worth can follow the change feed instead, as the collection app guide does.

Game night

With the numbers in columns, the rest is ordinary Sheets. Make a second sheet, put the number of players in B1 and the minutes you have in B2, and in A4:

=FILTER(Games!A2:A, Games!C2:C<=B1, Games!D2:D>=B1, Games!E2:E<=B2, (Games!G2:G="")+(LEFT(Games!G2:G, 7)="edition"))

That lists the games that seat that many and finish in time. The last condition keeps games and their editions and leaves out expansions, which need their base game on the table anyway. Games with no playtime in the catalog count as short enough, since an empty cell reads as 0. Put a friend's games in the same sheet and the list covers both shelves.

Where to go from here

  • Photos: each item has image with a thumb_url. The links are signed and expire after a few hours, so =IMAGE() on one stops working by the next day. Fetch them when you need them, from code that runs then.
  • A BoardGameGeek export: resolve also matches by BoardGameGeek ID ({ "external_id": "13", "source": "bgg" }), which is surer than a name. The collection app guide imports an export that way.
  • A game we are missing: send it with POST /v1/submissions, or add it in the web app. It is reviewed, then it is everyone's, and the Not in the catalog row fills in on the next run.