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;
}),
}),
});
scoresholds one row per game, with the player’s best score and the name to show.submitkeeps 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: () => ({}),
});
fromfills the index from everyPlayer’sscorestable.mapturns each row into an index row, andfrom.idis the key of the player it came from.columnsgives the index rows their types, whichindexesand 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.indexesadds an index onbestto the rows, for the top-ten read.onBeforeConnectlets 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.indexopens one partition of the index, here one game.findis a live read. It runs again as the partition’s rows change, and the app hears only a result that differs.typeof Leaderboardtypes 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
- Query across lunas covers indexes, partitions and reading your own write.
- Define tables covers primary keys and indexes on a luna’s own tables.
- Call lunas from TypeScript covers
createClientand index reads from apps.