Sikau

Node.js · Day 18 · about 60 min

Capstone: Orders API

Auth, validation, persistence and a Router.

Production-style

Write the orders router of a café API: protected by an API key, validated input, prices taken from the server's menu (never trust the client's prices), and orders saved to a JSON file.

The orders router, step by step

Read the whole task first and plan the order of checks before writing code.

This router is close to what you'd write at work: authentication, validation, server-side business rules and persistence, each in its proper place, ready for a real database next.

The capstone router combines the course: an API-key middleware guards every route, validation rejects bad input with a 400, prices come from the server's own menu, orders are saved to a JSON file with careful reads and writes, and responses use the right status codes. Each piece is something you've already written — the work is fitting them together cleanly.

router.use((req, res, next) => {
  if (req.get("x-api-key") !== "cafe-secret") return res.status(401).json({ error: "Unauthorized" });
  next();
});

router.post("/", async (req, res) => {
  const items = req.body?.items;
  if (!Array.isArray(items) || items.length === 0) return res.status(400).json({ error: "items required" });
  const lines = items.map(({ slug, qty }) => ({ dish: MENU.find((d) => d.slug === slug), qty }));
  if (lines.some((l) => !l.dish || !Number.isInteger(l.qty) || l.qty < 1)) return res.status(400).json({ error: "invalid item" });
  const total = lines.reduce((s, l) => s + l.dish.price * l.qty, 0);
  // … save and respond 201 …
});

The rest of this lesson

  • Never trust the clientexplain
  • Client-sent pricepredict
  • Handling POST /api/ordersorder
  • Situation → statusmatch
  • routes/orders.jschallenge
  • Badge quizquiz
  • Node.js complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 18 lessons of Node.js