Skip to content

Build a leaderboard with sorted sets

Working knowledgeBuild alongNode + RedisYou need: Build a REST API
What you’ll build: A leaderboard on top of your users API, kept in a Redis sorted set: record scores, keep each player’s best, read the top 10, and find any player’s rank and neighbours. Eight steps, each proved with a command.POST /leaderboardGET /leaderboard (top 10)GET /leaderboard/:playerGET /leaderboard/:player/around
Step 1 of 8

Bring in the users API you already built

Start from the finished project from Build a REST API from nothing: a folder users-api with Express installed, server.js, and the users routes in routes/users.js. If you no longer have it, make it again with the commands and the two files here.

WHY

Each step from here changes this project a little. Starting from known code means every diff you see is the new idea and nothing else.

This step runs:
terminal
$ mkdir users-api && cd users-api
$ npm init -y
$ npm install express
server.jsnew+14−0
Added: const express = require('express');
Added: const usersRouter = require('./routes/users');
Added: const app = express();
Added: app.use(express.json());
Added:
Added: app.get('/health', (req, res) => {
Added: res.json({ ok: true });
Added: });
Added:
Added: app.use('/users', usersRouter);
Added:
Added: app.listen(3000, () => {
Added: console.log('Listening on http://localhost:3000');
Added: });
routes/users.jsnew+24−0
Added: const express = require('express');
Added: const router = express.Router();
Added: const users = [];
Added:
Added: router.get('/', (req, res) => {
Added: res.json(users);
Added: });
Added:
Added: router.post('/', (req, res) => {
Added: if (!req.body?.name) {
Added: return res.status(400).json({ error: 'name is required' });
Added: }
Added: const user = { id: users.length + 1, name: req.body.name };
Added: users.push(user);
Added: res.status(201).json(user);
Added: });
Added:
Added: router.get('/:id', (req, res) => {
Added: const user = users.find((u) => u.id === Number(req.params.id));
Added: if (!user) return res.status(404).json({ error: 'Not found' });
Added: res.json(user);
Added: });
Added:
Added: module.exports = router;

Where to go next

Was this tutorial useful?Your vote tells us what to improve next.
Did a step not work, or something unclear?