Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

Build a leaderboard

Keep each player's best scores in a luna of their own, rank every player of a game with an index, and show the top ten live in an app.

At the end of this page you have a leaderboard for each game, with the top ten players shown live in an app. It uses one luna per player, an index filled from the players’ tables, and a live index read.

Each player is a Player luna that holds only their own scores. No luna can read another luna’s tables, so no Player can rank the others. An index can. Luna keeps a copy of every player’s score rows in it, which your lunas read and apps can read too.

Start from a project set up as in the Quickstart, with the TypeScript SDK installed.

The files

  • luna/
    • luna.config.ts
    • lunas/
      • index.ts
      • player.ts
      • leaderboard.ts
  • app/
    • leaderboard.ts
import { defineConfig } from "luna";

export default defineConfig({ lunas: "./lunas/index.ts" });
export { Player } from "./player.ts";
export { Leaderboard } from "./leaderboard.ts";

The player

import { defineLuna, t, table } from "luna";

export const Player = defineLuna({
  name: "Player",
  visibility: "public",
  key: { id: t.string() },
  schema: {
    scores: table({ game: t.string(), name: t.string(), best: t.int() }, { primaryKey: ["game"] }),
  },
  handlers: (h) => ({
    submit: h({ args: { game: t.string(), name: t.string(), score: t.int() } }, (ctx, { game, name, score }) => {
      const had = ctx.db.scores.get(game);
      if (had && had.best >= score) return had.best;
      ctx.db.scores.upsert({ game, name, best: score });
      return score;
    }),
  }),
});
  • scores holds one row per game, with the player’s best score and the name to show.
  • submit keeps a score only when it beats the best. It returns the best score either way.
  • Two submits at once take turns, so a lower score never overwrites a higher one.

A score that does not beat the best writes nothing, so the index changes only when a ranking can.

The index

import { defineIndex, t } from "luna";
import { Player } from "./player.ts";

export const Leaderboard = defineIndex("Leaderboard", {
  from: [
    Player.changes.scores.map((row, from) => ({
      game: row.game,
      player: from.id,
      name: row.name,
      best: row.best,
    })),
  ],
  columns: { game: t.string(), player: t.string(), name: t.string(), best: t.int() },
  partition: "game",
  indexes: [{ columns: ["best"] }],
  onBeforeConnect: () => ({}),
});
  • from fills the index from every Player’s scores table. map turns each row into an index row, and from.id is the key of the player it came from.
  • columns gives the index rows their types, which indexes and the app’s reads check against.
  • partition: "game" keeps each game’s rows in a partition of their own. A read names the game it wants.
  • indexes adds an index on best to the rows, for the top-ten read.
  • onBeforeConnect lets apps read the index directly. Returning without failing lets in every app with the publishable key.

The index is read-only. It changes only when a player’s scores table does, and its rows follow a little behind, once the player’s write has committed. A deploy that adds the index fills it from the players that already exist.

The app

import { createClient } from "luna/client";
import type { Leaderboard } from "../luna/lunas/leaderboard.ts";

const game = process.argv[2] ?? "chess";

const client = createClient({ url: process.env.LUNA_URL!, key: process.env.LUNA_KEY! });
const board = client.index<typeof Leaderboard>("Leaderboard", game);
const top = board.find({ orderBy: { best: "desc" }, limit: 10 });

top.subscribe(() => {
  const { data } = top.get();
  if (!data) return;
  console.log(`Top players in ${game}`);
  data.forEach((row, i) => console.log(`${i + 1}. ${row.name} ${row.best}`));
});
  • client.index opens one partition of the index, here one game.
  • find is a live read. It runs again as the partition’s rows change, and the app hears only a result that differs.
  • typeof Leaderboard types each row from the index’s columns.

Try it

Run luna dev, then load the URL and key it writes in a second terminal.

source .env.local

Submit a score for the player ann.

curl -X POST "$LUNA_URL/Player/ann/submit" \
  -H "luna-key: $LUNA_KEY" \
  -H "Content-Type: application/json" \
  -d '{"game":"chess","name":"Ann","score":1200}'

Show the chess leaderboard, then submit more scores for other players and watch it change.

node --env-file=.env.local app/leaderboard.ts chess

Next steps

Was this page helpful?