Exercise: Community Garden Server

Finish the community garden's server with Node's own http module, answering the list of plots, the free plots, one plot by its number and a JSON 404 for anything else, and let Supertest's tests check every answer.

Apprentice · Node.js · REST API · Updated

By

Greenleaf Community Garden still gets phone calls all day from neighbors asking which plots are free. You'll finish the garden's server so they can ask it instead: the list of plots, only the free ones, one plot by its number, and a clear 404 for anything else. It's built with Node's own node:http module, the way this chapter built the tool shed's server, and tests check every answer as you go.

Get the exercise code

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

Git makes a folder, exercise-node-garden-plots-server, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and install 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 request handler, app(req, res), for you to finish.
  • plots.js: the garden's eight plots. A free plot's gardener is null.
  • server.js: starts a server with your handler at http://localhost:3100.
  • garden.http: the requests to try with REST Client.
  • app.test.js: the tests, which send requests to your handler with Supertest. You don't need to change it.

What to do

app.js already exports the handler. For now it answers every request with a 404 that says it isn't built yet. The comment at its top lists every request it should answer:

//   GET /plots              200, every plot in plots.js
//   GET /plots?free=true    200, only the free plots (their gardener is null): plots 2, 5 and 8
//   GET /plots?free=false   200, every plot: only the text "true" means free
//   GET /plots/7            200, plot 7 (every plot's number works the same way)
//   GET /plots/99           404, { "message": "There's no plot 99." }
//   GET /plots/seven        404, { "message": "There's no plot seven." }
//   GET /compost            404, { "message": "There's nothing at /compost." }
//                           (any other path, named by its path without the query string)
  1. Read the address. Turn req.url into a URL, so you can read its path and its query values.
  2. Answer GET /plots with every plot, and with only the free ones when free is "true".
  3. Answer one plot by its number, such as GET /plots/7, or a 404 that names the number when there's no such plot.
  4. Answer everything else with a 404 that names the path.

Every answer, 404s included, sends Content-Type: application/json and a JSON body.

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 9 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 /plots/7 should answer 200, but it answered 404.

To try the server yourself, start it with npm start (or npm run dev, which restarts it each time you save), open garden.http, and click Send Request above each request. Stop it with Ctrl+C.

Hints

  • Give URL a base address. req.url holds only the path and query string, so new URL(req.url, "http://localhost:3100") fills in the rest, as HTTP in Plain Words: Requests and Responses shows. Then pathname is the path and searchParams.get("free") reads the query value.
  • Query values are text. "false" is text too, so check that free is exactly "true".
  • Split the path to find a plot's number. Routing by Hand, and Why Frameworks Exist splits /tools/3 into its parts and turns the 3 into a number with Number(). /plots/seven gives NaN, which matches no plot.
  • One helper for every answer. Each answer needs res.writeHead and res.end with JSON.stringify, as in A Web Server with Node's http Module. A small function that does all three keeps each answer to one line.
  • Answer once, then return. Otherwise the code carries on to the 404 at the bottom and tries to answer a second time.

When you're done

Every test is green, and with npm start running, garden.http's requests get these answers (each request, then its answer's status line and body):

GET /plots?free=true
HTTP/1.1 200 OK
[{"number":2,"size":"small","gardener":null,"growing":null},{"number":5,"size":"medium","gardener":null,"growing":null},{"number":8,"size":"large","gardener":null,"growing":null}]

GET /plots/7
HTTP/1.1 200 OK
{"number":7,"size":"small","gardener":"Priya","growing":"strawberries"}

GET /plots/99
HTTP/1.1 404 Not Found
{"message":"There's no plot 99."}

GET /compost
HTTP/1.1 404 Not Found
{"message":"There's nothing at /compost."}

Now look back at app.js. If the garden asked for one more address, say GET /gardeners, how many places in your code would change, and where would the new if have to go so the 404 still comes last?

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-garden-plots-server), 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-garden-plots-server.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-garden-plots-server, 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

Every API you'll build answers the same way this one does: read the method and the path, find the data, and send the right status code with JSON, 404s included. Express makes each of those shorter, starting in the next chapter, and you now know what it's doing underneath.

Key terms

Related