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
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'sgardenerisnull.server.js: starts a server with your handler athttp://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)
- Read the address. Turn
req.urlinto aURL, so you can read its path and its query values. - Answer
GET /plotswith every plot, and with only the free ones whenfreeis"true". - Answer one plot by its number, such as
GET /plots/7, or a 404 that names the number when there's no such plot. - 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
URLa base address.req.urlholds only the path and query string, sonew URL(req.url, "http://localhost:3100")fills in the rest, as HTTP in Plain Words: Requests and Responses shows. Thenpathnameis the path andsearchParams.get("free")reads the query value. - Query values are text.
"false"is text too, so check thatfreeis exactly"true". - Split the path to find a plot's number. Routing by Hand, and Why Frameworks Exist splits
/tools/3into its parts and turns the 3 into a number withNumber()./plots/sevengivesNaN, which matches no plot. - One helper for every answer. Each answer needs
res.writeHeadandres.endwithJSON.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.
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.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 mainPaste 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.