Exercise: Board Game Shelf API
Finish the board game café's Express API, with a games router that lists the games with filters for group size and playing time, finds one game by its id and adds a game, plus a timing middleware and a JSON 404, and let Supertest's tests check every answer.
Apprentice · Node.js · REST API · Updated
The Rolling Dice board game café keeps getting the same questions at the door: "Do you have something for four of us?", "Anything that's quick?". You'll finish the café's API so the café's app can answer them: a games router that lists the shelf with filters for group size and playing time, finds one game, and adds a donated game, plus a middleware that times every answer and a JSON 404 for any other address. It's built with Express, the way this chapter built the café's API, and tests check every answer as you go.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-node-board-game-shelf-api, also linked from the Exercise box beside the lesson. Clone it into your nodejs-course folder. In VS Code's terminal:
cd ~/nodejs-course
git clone https://github.com/ask-codey/exercise-node-board-game-shelf-api.git
Git makes a folder, exercise-node-board-game-shelf-api, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and install Express and the package the tests use:
npm install
Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder.
The folder holds:
app.js: the Express app,export const app = express(), for you to finish.routes/games.js: the games router,gamesRouter, with no routes yet, for you to finish.games.js: the café's eight games, andresetGames(), which the tests use to put the shelf back before each test.server.js: starts your app athttp://localhost:3100.shelf.http: the requests to try with REST Client.app.test.js: the tests, which send requests to your app with Supertest. You don't need to change it.
What to do
app.js already makes the app and exports it. For now it answers every request with a 404 that says it isn't built yet. The comment at its top lists every request the API should answer:
// GET /games 200, every game in games.js
// GET /games?players=4 200, only the games made for a group of 4 (minPlayers 4 or fewer and
// maxPlayers 4 or more): games 1, 2, 4 and 6
// GET /games?maxMinutes=30 200, only the games that take 30 minutes or less: games 2, 3, 5 and 6
// GET /games?players=4&maxMinutes=30 200, only the games that pass both filters: games 2 and 6
// GET /games?players=12 200, an empty list, []: no game is made for a group of 12
// GET /games/4 200, game 4 (every game's id works the same way)
// GET /games/99 404, { "message": "There's no game 99." }
// GET /games/chess 404, { "message": "There's no game chess." }
// POST /games 201, the new game, kept on the shelf. For the body
// { "title": "Lantern Festival", "minPlayers": 2, "maxPlayers": 4, "minutes": 35 }
// the answer is { "id": 9, "title": "Lantern Festival", "minPlayers": 2,
// "maxPlayers": 4, "minutes": 35, "available": true }: its id is one more than
// the number of games on the shelf, and a new game is always available
// GET /snacks 404, { "message": "There's nothing at /snacks." }
// (any other address, named by its path without the query string)
//
// Every answer, 404s included, carries the header X-Response-Time: how long the answer took, in milliseconds,
// with one digit after the point and "ms" after it, such as 0.8ms.
- List the games. In
routes/games.js, add the route forGET /gamestogamesRouter, with theplayersandmaxMinutesfilters, each used only when it was sent. - Find one game by its id, such as
GET /games/4, or answer a 404 that names the id when no game has it. - Add a game with
POST /games: build it from the body, push it ontogames, and answer 201 with it. - Put the app together in
app.js: the timing middleware that addsX-Response-Time,express.json(), the games router mounted at/games, and, last, a 404 for any other address. Replace the "Not built yet." middleware.
Check your work
Run the tests from the exercise folder:
npm test
No server needs to be running: the tests hand each request straight to app, which is why app.js and server.js are separate files. At first all 13 tests fail. That's expected: each request you answer turns its test green. A failing test's message says what it sent and what it expected, for example GET /games/4 should answer 200, but it answered 404.
To try the API yourself, start it with npm start (or npm run dev, which restarts it each time you save), open shelf.http, and click Send Request above each request. Stop it with Ctrl+C.
Hints
- Inside the router, leave
/gamesout.app.use("/games", gamesRouter)mounts it, so the router's paths are"/"and"/:id", as Organizing Routes with express.Router shows. - Everything in an address is text.
req.params.idandreq.query.playersare text, so turn them into numbers withNumber()before comparing, as Route and Query Parameters does."chess"becomesNaN, which matches no game. - A filter that wasn't sent is
undefined. Start with every game and narrow the list once for each filter that's there, soGET /gamesstill answers all eight and both filters can apply at once. - The body needs
express.json(). Without it,req.bodyisundefined, as Your First Express App: Routes and JSON shows. Choose 201 withres.status(201)before.json. - Time every answer with one middleware, added first. Middleware: Code That Runs on Every Request builds the one that wraps
res.writeHeadto addX-Response-Time. Added before the router and the 404, it times those answers too. - The 404 for other addresses goes last. A middleware after the router answers only what no route answered.
req.pathis the path without the query string.
When you're done
Every test is green, and with npm start running, shelf.http's requests get answers like these (each request, then its answer's status line, the timing header and the body). Your times will differ:
GET /games?players=4&maxMinutes=30
HTTP/1.1 200 OK
X-Response-Time: 1.4ms
[{"id":2,"title":"Moon Mice","minPlayers":3,"maxPlayers":6,"minutes":20,"available":false},{"id":6,"title":"Word Garden","minPlayers":2,"maxPlayers":8,"minutes":25,"available":false}]
GET /games/chess
HTTP/1.1 404 Not Found
X-Response-Time: 0.2ms
{"message":"There's no game chess."}
POST /games
HTTP/1.1 201 Created
X-Response-Time: 6.6ms
{"id":9,"title":"Lantern Festival","minPlayers":2,"maxPlayers":4,"minutes":35,"available":true}
GET /snacks
HTTP/1.1 404 Not Found
X-Response-Time: 0.3ms
{"message":"There's nothing at /snacks."}
Now look back at routes/games.js and app.js. If the café added its tables as a second resource, which files would change, and which would stay exactly as they are?
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.
On GitHub, click +, then New repository. Name it (for example
exercise-node-board-game-shelf-api), choose Public, and click Create repository. Leave out the README: your folder already has one.In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:
git remote set-url origin https://github.com/your-name/exercise-node-board-game-shelf-api.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-node-board-game-shelf-api, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.
So what
Routes in a router, filters from the query string, one item by its id, a POST that answers 201, and middleware for the jobs every request shares: that's the shape of the Express APIs you'll build from here on, and the next chapter makes this one check what it's sent.