Exercise: Bike Repair Tickets

Finish Spoke & Chain's tickets API with Express and Zod, checking every new ticket, moving a ticket only to its next status, deleting with 204, and answering every error in one JSON shape, and let Supertest's tests check every answer.

Journeyman · Node.js · REST API · Updated

By

Spoke & Chain Bike Repair's front desk and its mechanics' phones are about to share one tickets API, and they all need it to behave the same way every time: tickets checked before they're saved, bikes that move through the shop one step at a time, and errors a phone app can always read. You'll finish that API with Express and Zod, the way this chapter built it, and tests check every answer as you go.

Get the exercise code

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

Git makes a folder, exercise-node-bike-repair-tickets, 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 the app and its 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.
  • tickets.js: the shop's five tickets, nextId() for a new ticket's id, and resetTickets(), which the tests use to start each test fresh.
  • report.js: the end-of-day report, which fails every time on purpose, so your error handler has a real error to handle.
  • server.js: starts the app at http://localhost:3100.
  • tickets.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 switches on express.json(). For now it answers every request with a 404 that says it isn't built yet, except GET /report, a ready route that fails. The comment at its top lists every request it should answer. Its first lines set out the error shape and the ticket endpoints:

// Answer each request below with its status code and a JSON body. Every error answer has the API's one shape:
//   { "status": 404, "title": "Not Found", "detail": "There's no ticket 99." }
// title is the status code's name, STATUS_CODES[status] from node:http. A 400 for a body that breaks a rule also has
// "problems": a list of { "field": "...", "message": "..." }, one for each field that breaks a rule (word the
// messages as you like). No error answer ever holds anything else, such as a stack trace.
//
//   GET    /tickets      200, every ticket in tickets.js
//   GET    /tickets/2    200, ticket 2 (every ticket's id works the same way)
//   GET    /tickets/99   404, detail "There's no ticket 99."
//
//   POST   /tickets      201, the new ticket, also added to tickets:
//                          { id: nextId(), customer, bike, problem, status: "waiting" }
//                        customer, bike and problem come from the body, with the spaces at their ends trimmed off.
//                        The rules: customer, bike and problem are text that isn't empty once trimmed, and problem
//                        is 200 characters or fewer. Any other field in the body, such as id or status, is ignored.
//                        400 when a rule is broken: detail "The ticket isn't valid.", problems naming each field
//                        that broke one. Nothing is saved.

The rest of the comment covers PATCH (one step at a time: waiting, in repair, ready, picked up; 404, then 400, then 409 for a step that skips ahead or goes back), DELETE (204, or 404), any unknown path (404), a body that isn't valid JSON (400) and GET /report (500).

  1. Write a helper that sends the error shape, so every error answer is one line.
  2. Answer the two GET routes: every ticket, and one ticket by its id or a 404.
  3. Add a ticket with POST, checked by a Zod schema, answering 201 with the new ticket or 400 with every problem.
  4. Move a ticket with PATCH, checking the status with a second schema, then whether it's the ticket's next step.
  5. Remove a ticket with DELETE, answering 204 with no body.
  6. Finish the bottom of the file: a 404 handler after every route, then error-handling middleware that answers a body that isn't JSON with 400 and everything else with 500.

Check your work

Run the tests from the exercise folder:

npm test

No server needs to be running, and the tickets start fresh before every test. At first all 19 tests fail. That's expected: each answer you build turns its tests green. A failing test's message says what it sent and what it expected, for example GET /tickets/2 should answer 200, but it answered 404. Test 19 makes the report fail on purpose, so once your error handler logs errors, that error shows in the test output; that's your log doing its job.

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

Hints

  • Start with the error shape. Error Handling and Consistent Error Responses builds sendProblem with STATUS_CODES; with it, every 404, 400, 409 and 500 is one line.
  • Let the schema do the cleaning. Validating with Zod shows that .trim() trims, .min(1) refuses empty text, and a Zod object drops fields it doesn't list, such as an id or a status in a new ticket's body. Build the ticket from result.data.
  • Two checks for a status change. First the schema (is it one of the four statuses? if not, 400), then the shop's rule (is it this ticket's next step? if not, 409). An object such as { "waiting": "in repair", ... } gives the next step in one lookup.
  • 204 has no body. Designing REST Endpoints: Create, Update and Delete finishes a DELETE with res.status(204).end().
  • The bottom of the file is in order: every route, then the 404 handler, then the error handler with all four parameters, (err, req, res, next).

When you're done

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

POST /tickets  { "customer": " Lena ", "bike": "folding bike", "problem": "gears won't shift" }
HTTP/1.1 201 Created
{"id":6,"customer":"Lena","bike":"folding bike","problem":"gears won't shift","status":"waiting"}

PATCH /tickets/1  { "status": "in repair" }
HTTP/1.1 200 OK
{"id":1,"customer":"Dana","bike":"blue cruiser","problem":"flat rear tire","status":"in repair"}

PATCH /tickets/5  { "status": "ready" }
HTTP/1.1 409 Conflict
{"status":409,"title":"Conflict","detail":"Ticket 5 is waiting, so it can't go to ready."}

DELETE /tickets/3
HTTP/1.1 204 No Content

GET /bikes
HTTP/1.1 404 Not Found
{"status":404,"title":"Not Found","detail":"There's nothing at /bikes."}

GET /report
HTTP/1.1 500 Internal Server Error
{"status":500,"title":"Internal Server Error","detail":"Something went wrong on our side."}

Now look back at app.js. If the shop added a fifth status, say "waiting for parts" between in repair and ready, how many places in your code would change? And if a phone app's developer asked you how to read your errors, could you answer in one sentence?

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-bike-repair-tickets), 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-bike-repair-tickets.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-bike-repair-tickets, 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

Checked input, honest status codes and one error shape are what turn a handful of routes into an API other people can build on. The next chapter writes the tests yourself, so you can prove all of it whenever the code changes.

Key terms

Related