Start learning free

LESSON 143 OF 173 · BACKEND: TESTS AND RUNNING IT

A Health Check

Practice

A shop on a server can stop working while you sleep. A monitoring service notices it for you: every minute it asks the shop a simple question over HTTP, and alerts you when the answer is wrong or doesn't come. The question is a health check, a route made only for this. A good one really asks the parts the shop needs, like its database, and says which one is down.

Asking can fail: when the database can't answer, the query throws an error, and an error that nobody catches ends the route with a 500. Put the risky line in a try block, and when it throws, JavaScript jumps to the catch part instead of crashing. For example, in a route that reads a text as JSON:

let data;
try {
  data = JSON.parse(text);
} catch (error) {
  return res.status(400).json({ error: "The body must be JSON" });
}

The cheapest question for a database is SELECT 1: it reads no table and just answers 1. While the database is down, the health check still answers 200 with status ok, because the shop itself answers; its database part tells you where to look.

The check plays the monitor, stops the database for a minute, then lets it answer again:

GET /health  →  200  {"database": "ok", "status": "ok"}
(the database stops answering)
GET /health  →  200  {"database": "down", "status": "ok"}
GET /products/count  →  500  (an HTML error page)
(the database answers again)
GET /health  →  200  {"database": "ok", "status": "ok"}

Your task: add GET /health, which asks the database SELECT 1 and answers { status: "ok", database: "ok" }, or "down" for the database when the query throws an error. Then write the test "health", which checks the status and the whole JSON body. The check runs it on the shop, where it must pass, and on a copy whose health query has a typo, so it always says down, where it must fail.


Assignment
Follow the Coding Tutorial to build the /health route and a test that checks its whole answer.


Hint
The query goes inside the try part, and the down answer inside catch, with return in front so the route stops there. A test that checks only the 200 lets the typo copy through: compare response.body too, with assert.deepStrictEqual.


STEP 1 OF 10
    Ctrl + Enter to check