Exercise: Shuttle Schedule API

Get the campus shuttle's API ready for real riders, with settings checked by Zod at startup, a pino-http log line for every request with tokens and the database address redacted, a /health route that answers 200 or 503, and a graceful shutdown, and let the tests check each one.

Journeyman · Node.js · Web Development · Updated

By

The Campus Shuttle API already answers riders: every route, and one route by its id. Before the college puts it online for real riders, the team wants what this chapter taught: settings checked when the server starts, a log line for every request with secrets hidden, a health check the host can call, and a shutdown that never cuts off a rider. You'll build all four, and tests check each one, with a throwaway MongoDB, so you don't need a database running to check your work.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-node-shuttle-schedule-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-shuttle-schedule-api.git

Git makes a folder, exercise-node-shuttle-schedule-api, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and install the packages:

npm install

Then copy .env.example to .env: it holds the three settings, with values for your own computer. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder.

The folder holds:

  • config.js: loadConfig(env), for you to finish.
  • logger.js: createLogger(level, destination) and createRequestLogger(logger), for you to finish.
  • app.js: createApp(db), which builds the Express app around the database it's given, as in Wiring MongoDB into Express. GET /routes and GET /routes/:id work; the request logger and GET /health are for you to add.
  • shutdown.js: shutdown({ server, client, logger, signal }), for you to finish.
  • server.js: loads the settings, connects to MongoDB, starts the API at the port in PORT, and calls shutdown on Ctrl+C or SIGTERM. Ready to use.
  • shuttle.js and sample-routes.js: the shuttle's three routes, kept in MongoDB, and createShuttleRepository(db), the repository createApp makes, with pingDatabase(). Ready to use.
  • shuttle.http: the requests to try with REST Client.
  • config.test.js, logger.test.js, app.test.js, shutdown.test.js and throwaway-database.js: 14 tests, and the throwaway MongoDB they use. You don't need to change them.

What to do

Each file you finish has a comment at its top that says exactly what it must do. For now, each one either throws Not built yet. or does nothing, so all 14 tests fail. Work through them in this order, running one test file at a time with node --test config.test.js and so on:

  1. config.js: settings checked at startup (tests 1 to 6). loadConfig(env) gives back { port, mongodbUri, logLevel }, or throws one error naming every problem:

    //   PORT          optional, 3100 when it isn't set; a whole number from 1 to 65535, given back as a number
    //                 its problem: "PORT must be a whole number from 1 to 65535"
    //   MONGODB_URI   required; it starts with mongodb:// or mongodb+srv://
    //                 its problems: "MONGODB_URI is missing" (not set at all)
    //                               "MONGODB_URI must start with mongodb:// or mongodb+srv://" (set to anything else)
    //   LOG_LEVEL     optional, "info" when it isn't set; one of fatal, error, warn, info, debug, trace or silent
    //                 its problem: "LOG_LEVEL must be fatal, error, warn, info, debug, trace or silent"
    //
    // When any setting has a problem, loadConfig throws one Error whose message names every problem, in the order above,
    // joined by "; ", after "Fix these settings, then start again: " and ending with a period:
    //   "Fix these settings, then start again: PORT must be a whole number from 1 to 65535; MONGODB_URI is missing."
    
  2. logger.js: logs with secrets hidden (tests 7 to 9). createLogger(level, destination) gives back a pino logger at that level that writes [Redacted] for req.headers.authorization, req.headers.cookie and config.mongodbUri. createRequestLogger(logger) gives back pino-http middleware with that logger.

  3. app.js: request logs and a health check (tests 10 and 11). Use createRequestLogger(logger) before the routes. Add GET /health: it calls shuttle.pingDatabase() and answers 200 with { "status": "ok" }, or, when the ping fails, logs req.log.warn({ err: error }, "Health check: the database didn't answer") and answers 503 with { "status": "unavailable" }.

  4. shutdown.js: a graceful shutdown (tests 12 to 14). Log { signal } with Shutting down: finishing the requests in progress, close the server and wait until every request in progress has its answer, then close the database client, then log Closed the server and the database connection. Both lines are info.

Check your work

Run every test from the exercise folder:

npm test

No server and no MongoDB need to be running: the tests hand requests straight to the app createApp(db) builds, and start a throwaway MongoDB of their own (the first run may download one, once per computer). A failing test's message says what it expected and what it got, for example GET /health should answer 200, but it answered 404.

To try the API yourself, start MongoDB as in Setup: MongoDB and Compass, then run npm run dev, which restarts the server each time you save and shows the logs through pino-pretty. Open shuttle.http and click Send Request above each request. Press Ctrl+C to watch the shutdown.

Hints

  • Settings are text. z.coerce.number() turns "3200" into 3200 before the checks; Configuration Checked at Startup has a schema very close to this one.
  • One message for every problem. safeParse gives back every problem in error.issues, in the order the schema lists the settings. Give each check its own message with { error: "..." }, then map the issues to their messages and join("; ").
  • Redact paths start where the value sits in the line. pino-http puts the request under req, and server.js logs the settings under config; Logging with pino shows the option.
  • req.log exists only after the request logger. If test 11 says /health answered 500, the route threw, usually because req.log isn't there yet.
  • Wait for server.close. It takes a function it calls when the last request has its answer. await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))) waits for it; Graceful Shutdown and Health Checks shows a shorter form.

When you're done

Every test is green. With MongoDB running and .env copied from .env.example, npm start writes these lines (shortened here: each request's line also holds its headers), and shuttle.http's requests get these answers:

{"level":30,"time":1794940140956,"pid":127232,"hostname":"sams-laptop","config":{"port":3100,"mongodbUri":"[Redacted]","logLevel":"info"},"msg":"Settings loaded"}
{"level":30,"time":1794940140985,"pid":127232,"hostname":"sams-laptop","msg":"The Campus Shuttle API is listening on http://localhost:3100"}
GET /routes/blue-loop
HTTP/1.1 200 OK
{"id":"blue-loop","name":"Blue Loop","every":10,"firstBus":"7:00","lastBus":"22:50","stops":["library","science-hall","stadium","north-dorms"]}

GET /routes/purple-line
HTTP/1.1 404 Not Found
{"status":404,"title":"Not Found","detail":"There's no route purple-line."}

GET /health
HTTP/1.1 200 OK
{"status":"ok"}

The request with a token is logged with "authorization":"[Redacted]", and Ctrl+C ends with:

{"level":30,"time":1794940141861,"pid":127232,"hostname":"sams-laptop","signal":"SIGINT","msg":"Shutting down: finishing the requests in progress"}
{"level":30,"time":1794940141863,"pid":127232,"hostname":"sams-laptop","msg":"Closed the server and the database connection"}

Now try a mistake on purpose: set PORT=31OO in .env and run npm start. It stops at once with Fix these settings, then start again: PORT must be a whole number from 1 to 65535. Put it back to 3100 when you're done. Then think about the next step: if riders said the routes list felt slow, which tool from Performance Basics: Measure First would you run first, and on which address?

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.

  1. On GitHub, click +, then New repository. Name it (for example exercise-node-shuttle-schedule-api), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. 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-shuttle-schedule-api.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-node-shuttle-schedule-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.

.env stays on your computer: it's in .gitignore, so git add . leaves it out. Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

Settings checked at startup, logs with nothing secret in them, a health check and a graceful shutdown are what separate an API that works on your laptop from one a team trusts with real riders, and you'll set up the same four in every API you put online.

Key terms

Related