Node.js & Express — Practice

Build the review routes on an in-memory store (Session 4)

Practice
Node.js
Express
Backend
AI-Assisted Development
Author
Affiliations

Université de Toulon

LIS UMR CNRS 7020

Published

2026-10-20

Abstract

Course lectures and practices for JavaScript full‑stack web development with AI‑assisted workflows.

Note

All AI prompts in this practice are starting points — feel free to reword them to match your style. The skill you are practising is not “copy the prompt”; it is verifying what the AI writes against the checklists below. You are the quality gate on the generated code. Using a coding agent is optional from Session 3 onward — verifying its output is not.

Overview

Where you are. In Session 3 (React review practice) you built the React review UI. Today you build the backend review routes it calls — first on an in-memory store (MySQL arrives in Session 5). Read the Session 4 lecture first — it covers the concepts (Express, routing, the in-memory store, 404-early, the response envelopes); this practice is where you build and verify them.

Goal — extend the existing fullstack-minimal-app/backend Express app (do not start a new project — you extend it in place, in ESM) with:

  1. an in-memory review store in backend/src/data/reviews.js — a Map keyed by product id, seeded with the 8-field reviews;
  2. GET /api/products/:id/reviews → { data, meta: { count } }, 404-early;
  3. GET /api/products/:id/aggregate → { data: { overall_avg, per_source, histogram, count } }, 404-early, safe on a product with zero reviews;
  4. live wiring: point the S3 review hook at these two routes so the React UI renders from your API (Tasks 4–5 — required).

In Session 4 the reviews live in the in-memory store — no new database table and no live scraping (the product-existence check keeps using the existing MySQL product DB on :3306). The API exposes the 8-field review shape; rating is an integer 1–5; and the product_id join column only appears in Session 5’s table. The third canonical route, POST /api/products/:id/fetch (against the shipped scraper-service/ on :5000), is the S5 home stretch — you do not build it today.

The AI-first pattern (CRISP)

Every task below follows the same four steps (CRISP):

Step What you do
Concept 1–3 lines on what you are building and why it matters.
AI generates Give the assistant the CRISP, copy-paste prompt in the box.
You verify Run it, then check it against the common AI mistakes for this task list. Fix what fails.
You integrate Confirm the checkpoint (what “done” looks like) and make the git commit.
Tip

If the AI’s output fails any item on a checklist, do not just copy it — tell the AI which item failed and ask it to fix only that. That back-and-forth is the skill.

Setup & running the app

This practice builds against the course’s real app, fullstack-minimal-app (develop). It has an Express backend on http://localhost:4000 (the React/Vite frontend from S3 is on :5173, but you will need it from Task 4 onward).

1. Get the app (if you have not already):

git clone https://github.com/ebpro/fullstack-minimal-app.git
cd fullstack-minimal-app

2. Start the backend (so it listens on :4000):

cd fullstack-minimal-app/backend
npm install
npm run dev        # or `npm start` — see the README

2b. Bring up the database. From the app root (fullstack-minimal-app/), run docker compose up --build — the app README’s quickstart. The product routes are 100% MySQL-pool-backed with no seed or in-memory fallback, so without this the catalog curl below — and Task 4’s “catalog renders” gate — cannot pass.

3. Verify the app is up — and that the review routes do NOT exist yet (building them is this practice):

curl http://localhost:4000/health
curl http://localhost:4000/api/products
curl http://localhost:4000/api/products/1/reviews
  • curl http://localhost:4000/health — should respond ({ status: "ok", ... }).
  • curl http://localhost:4000/api/products — returns the catalog in a { data, meta } envelope.
  • curl http://localhost:4000/api/products/1/reviews — should 404 today. That route is exactly what you will add in Task 2.

Task 1 — the in-memory review store

Concept. The reviews are not in MySQL yet (that is Session 5 — S4 adds no new database table), so you hold them in a Map in backend/src/data/reviews.js — product id → array of the 8-field reviews — that the routes import. The store is the only thing the review routes depend on for review data; in Session 5 you swap it for the reviews table by changing the bodies of the two helpers, not the routes.

AI generates

Tip

Copy-paste this prompt to your assistant:

Context: Express 4.18 backend (`fullstack-minimal-app/backend`, ESM, Node 22). In S4 reviews live
in the in-memory store `src/data/reviews.js`; the MySQL reviews table arrives in S5. The product
catalog already lives in MySQL (`src/db.js` exports the pool).
Task: Create `src/data/reviews.js` exporting the store and its two helpers.
Requirements:
- `const reviewsByProduct = new Map()` seeded for products '1', '2' and '3' (string keys — route
  params arrive as strings), with realistic e-commerce review text.
- Each review has EXACTLY 8 fields: review_id (a string like 'AMZ_0001'), source (one of
  Amazon|BestBuy|Walmart), author, rating (an integer 1–5), title, body, created_at (an ISO
  timestamp string), verified_purchase (a boolean). No "was this useful?" flag and NO product_id
  field (that join column exists only in Session 5's table).
- Export `getProductReviews(id)` returning `reviewsByProduct.get(String(id)) ?? []`.
- Export `aggregateProductReviews(id)` returning `{ overall_avg, per_source, histogram, count }`:
  overall_avg is the mean rating rounded to 2 decimals, per_source is a map keyed by source name
  holding one 2-decimal mean per source present (no per-source count),
  histogram the buckets 1..5 with all five keys always present (even when 0), count the number
  of reviews.
- Empty case: a product with no reviews must return overall_avg null, count 0 and all five
  histogram buckets at 0 — never NaN, never divide by zero.
Constraints: ESM only (`export ...`, no `require`); the store must not import from the routes.
Output: only the new `src/data/reviews.js` file.

The canonical aggregate body — what aggregateProductReviews returns and what the aggregate route sends as data. per_source is a map, one key per source present, no per-source count: the shape and the key names below are the contract, the values are not — they come from a seed you wrote yourself, so a different overall_avg or count is your data, not your bug.

{
  "overall_avg": 3.56,
  "per_source": { "Amazon": 4.33, "BestBuy": 3.67, "Walmart": 2.67 },
  "histogram": { "1": 0, "2": 1, "3": 3, "4": 4, "5": 1 },
  "count": 9
}

You verify — common AI mistakes for this task

  • Wrong keys. The Map is keyed by the string ids '1', '2', '3' — route params arrive as strings, and the lookup is reviewsByProduct.get(String(id)) ?? []. Numeric keys 1, 2, 3 would never match.
  • Extra or missing fields. Every review has exactly the 8 canonical fields — no “was this useful?” flag, no product_id (that join column only exists in Session 5’s table).
  • Rating out of range. rating is an integer 1–5 — no 0, no 6, no floats.
  • CommonJS. The file must be ESM (export ...), like the rest of backend/src.
  • Aggregate math. For a product, aggregateProductReviews returns histogram keys 1..5 whose values sum to count; per_source contains each source that is present; an empty product returns overall_avg: null, count: 0, and all five histogram buckets at 0.

You integrate

Checkpoint. From backend/, print product 1’s aggregate — you should see the 1–5 histogram, the per-source means, and count; then print an unseeded product — it must show the safe empty shape (overall_avg: null, count: 0, all five buckets at 0, no NaN):

node -e "import('./src/data/reviews.js').then(m => console.log(m.aggregateProductReviews('1')))"
node -e "import('./src/data/reviews.js').then(m => console.log(m.aggregateProductReviews('99')))"

Then lock it in:

git add src/data/reviews.js && git commit -m "feat(backend): in-memory review store (8-field, 1-5) + aggregate helper"

Task 2 — GET /:id/reviews

Concept. 404-early: confirm the product exists in the existing MySQL product table before touching the in-memory store — an unknown product id must 404 whether or not it happens to have reviews. Then return the store’s reviews in the { data, meta } envelope the S3 React frontend already reads.

AI generates

Tip

Copy-paste this prompt to your assistant:

Context: Express 4.18 router `src/routes/products.js` (ESM, mounted at /api/products, so the full
path matters). `pool` is already imported from `../db.js`; Task 1's `getProductReviews` lives in
`../data/reviews.js`. The S3 React frontend reads the `{ data, meta }` envelope.
Task: Add one route so its full path is GET /api/products/:id/reviews.
Requirements:
- 404-early: first confirm the product exists with a parameterized SELECT on the products table;
  if it does not, return 404 { error: 'Product not found' } BEFORE reading the store.
- Success: respond { data: [review...], meta: { count } } with the store's reviews for :id.
Constraints: inline async (req, res, next) handler with plain try/catch forwarding to next(err);
no handler wrapper, no custom error class; import getProductReviews from ../data/reviews.js;
do not touch the existing CRUD routes; do not query any reviews table (S4 has none).
Output: only the import line and the new route block.

You verify — common AI mistakes for this task

With the backend running on :4000, run the two curls and check each response:

  • curl http://localhost:4000/api/products/1/reviews — returns { data: [...8-field reviews...], meta: { count } }.
  • curl http://localhost:4000/api/products/999/reviews — returns 404 { error: 'Product not found' }. If it returns an empty list instead, the store is being read before the product check (404-early is missing).
  • Every returned review has exactly the 8 fields and a rating of 1–5.
  • The route keeps the inline async (req, res, next) handler with next(err) in the catch — no wrapper helper, no custom error class.

You integrate

Checkpoint. Both curls above behave as specified (200 with the envelope for a real product, 404 for an unknown one). Then lock it in:

git add src/routes/products.js && git commit -m "feat(backend): GET /:id/reviews (in-memory, 404-early, {data,meta})"

Task 3 — GET /:id/aggregate

Concept. Same 404-early rule as Task 2: confirm the product exists in the existing MySQL product table before touching the in-memory store. Then compute the aggregate from the in-memory reviews and return it in the { data } envelope — the aggregate has no meta (that belongs only to the list route). A real product with zero reviews must still return a valid, deterministic aggregate (no crash, no NaN).

AI generates

Tip

Copy-paste this prompt to your assistant:

Context: the same router `src/routes/products.js`; Task 1's `aggregateProductReviews` lives in
`../data/reviews.js`.
Task: Add one route so its full path is GET /api/products/:id/aggregate.
Requirements:
- 404-early: the same parameterized product-existence check as the reviews route; return 404
  { error: 'Product not found' } before touching the store when the product does not exist.
- Success: respond { data: aggregate } where aggregate is what aggregateProductReviews(:id)
  returns — { overall_avg, per_source, histogram, count }. No `meta` on this route.
- The zero-review case must be safe: overall_avg null, count 0, all five histogram buckets 0 —
  never NaN, never divide-by-zero.
Constraints: inline async (req, res, next) handler with plain try/catch forwarding to next(err);
delegate all aggregation math to aggregateProductReviews — do not recompute it in the route;
do not query any reviews table (S4 has none).
Output: only the added route block (and its import if not already present).

You verify

With the backend running on :4000, run the curls and check each response:

  • curl http://localhost:4000/api/products/1/aggregate — returns { data: { overall_avg, per_source, histogram, count } }, where histogram has all five keys 1..5 (every bucket present even when its count is 0).
  • curl http://localhost:4000/api/products/999/aggregate — returns 404 { error: 'Product not found' }.
  • curl http://localhost:4000/api/products/4/aggregate (a real product the store did not seed) — returns 200 with overall_avg: null, count: 0 and all five histogram buckets at 0 — never NaN, never a divide-by-zero crash.
  • overall_avg and every value in the per_source map are numbers rounded to 2 decimals (the canonical body is printed in Task 1).
Warning

If your per_source came out as an array of { source, average } objects, the course text is at fault. The course text was ambiguous here: Session 3 named the per-source key by_source and nested the headline as overall.average, while Session 4 named it per_source with a flat overall_avg — so a reasonable student built either. The canonical aggregate is the flat body printed in both sessions. The canonical shape is a map keyed by source name, with no per-source count. Fix it in aggregateProductReviews in src/data/reviews.js (build the map there), not in the frontend: the frontend consumes the backend’s shape, so correcting it upstream means no adapter ever has to exist.

You integrate

Checkpoint. Both curls above behave as specified (200 with the { data } envelope for a real product, 404 for an unknown one). Then lock it in:

git add src/routes/products.js && git commit -m "feat(backend): GET /:id/aggregate (in-memory, 404-early, {data})"

Task 4 — point the S3 hook at your API

Concept. In Session 3, frontend/src/hooks/useProductReviews.js resolved the local SAMPLE_REVIEWS; Tasks 2–3 gave you the routes that curl can reach. From here the browser actually calls them. This is a pure transport swap: the shapes already agree after the Session 3 correction, so you change where the data comes from — no key renaming anywhere.

First, one env step (do not skip it). Your hook carries its own || 'http://localhost:4000' fallback, so the review requests themselves do not need an env file. The app’s product catalog does: App.jsx reads import.meta.env.VITE_BACKEND_URL || '/api' and the Vite dev server has no /api proxy — without .env the catalog never loads and you cannot even reach a product page. From frontend/:

cp .env.example .env    # ships VITE_BACKEND_URL=http://localhost:4000; .env is gitignored — never commit it
npm run dev             # (re)start Vite — .env is only read at startup

Observable result: the catalog renders at http://localhost:5173.

AI generates

Tip

Copy-paste this prompt to your assistant:

Context: `frontend/src/hooks/useProductReviews.js` from Session 3. It exports
`useProductReviews(productId)` returning `{ reviews, aggregate, loading, error }`, resolves
`SAMPLE_REVIEWS` inside a single `useEffect` keyed on `[productId]`, and uses a `cancelled` cleanup
flag. Your S4 backend serves GET /api/products/:id/reviews returning `{ data, meta: { count } }`.
Task: Replace the SAMPLE_REVIEWS resolution with a real fetch of that route — transport only.
Requirements:
- Use `const API_BASE = import.meta.env.VITE_BACKEND_URL || 'http://localhost:4000'` (already
  defined in the hook from Session 3) and build the request URL from `API_BASE`; no literal URL
  inside the fetch.
- Read the list from `json.data`; keep the public shape `{ reviews, aggregate, loading, error }`
  unchanged.
- Keep the single `useEffect` keyed on `[productId]` and the `cancelled` cleanup flag; only the
  reviews data source changes.
- Do NOT touch how `aggregate` resolves in this task — it gets its own swap in Task 5.
- Do NOT rename or map any field: the objects the backend serves use the same keys the S3
  components already consume.
Constraints: plain `fetch` with `async`/`await` inside the existing effect; no new dependency.
Output: only the modified `useProductReviews.js`.

You verify

  • DevTools → Network on a seeded product page: a request to :4000/api/products/<id>/reviews returns 200 with the { data, meta } envelope.
  • Greppable: frontend/src/hooks/useProductReviews.js contains import.meta.env.VITE_BACKEND_URL and the fetch(...) URL is built from API_BASE — not a hardcoded literal URL.
  • Stale key remnant: by_source was the pre-correction S3 key and must appear nowhere in the hook — grep -c "by_source" src/hooks/useProductReviews.js prints 0. This item detects a stale key remnant; it is not evidence that no mapping code exists.
  • The hook still has exactly one useEffect, keyed on [productId] (not [id] — that spelling only belongs to the useParams caller), with the cancelled flag and the same public shape.

You integrate

Warning

Negative test — required before you move on. Stop the backend (Ctrl-C in its terminal) and reload http://localhost:5173. The review list must go empty or show its error state. Restart the backend — the list returns. If the reviews still render with your backend stopped, you are still reading SAMPLE_REVIEWS.

Checkpoint. Re-word one review’s title or body in backend/src/data/reviews.js and reload the product page: your new text appears. (Only npm run dev hot-reloads — if you started the backend with npm start, restart it before reloading.) Then lock it in, from frontend/:

git add src/hooks/useProductReviews.js && git commit -m "feat(frontend): hook fetches GET /:id/reviews (json.data)"

Task 5 — the aggregate panel, now live

Concept. The same transport swap for the second route: the hook must read the aggregate from GET /api/products/:id/aggregate, which serves it under { data } — the flat shape { overall_avg, per_source, histogram, count } your corrected S3 components already consume. The 2-decimal average, the per-source averages, the 1–5 histogram and the safe empty case now come from the backend. No adapter code — the JSON is used as-is.

Preflight — migrate your S3 panel first (required, before you prompt). This is not a “if your panel looks different” check: if you did Session 3 as delivered, your frontend is incompatible with this backend on all three axes — S3 named the per-source key by_source (S4: per_source), nested the headline as overall.average / overall.count (S4: flat overall_avg / count), and rounded to 1 decimal (S4: 2 decimals). Do this first:

  1. Open the Session 3 correction and migrate the two frontend files — ReviewStats and the hook’s aggregate resolution — to the canonical shape.
  2. The authority is the canonical aggregate body printed in Task 1 of this file: keys and nesting exactly as printed there.
  3. Fix the upstream components. Do not write a mapping layer between the API and the panel — the promise of Tasks 4–5 is that the JSON is consumed as-is.

AI generates

Tip

Copy-paste this prompt to your assistant:

Context: the hook `frontend/src/hooks/useProductReviews.js`, after Task 4 (the list route is already
fetched from `API_BASE = import.meta.env.VITE_BACKEND_URL`). Your S4 backend serves
GET /api/products/:id/aggregate returning `{ data: { overall_avg, per_source, histogram, count } }`
— the same keys Session 3's ReviewStats consumes.
Task: Replace the hook's local aggregate resolution with a fetch of that route — transport only.
Requirements:
- Build the URL from `API_BASE` (same constant as Task 4); read the value from `json.data` and store
  it unchanged — no key renaming, no remapping, no per-field defaults.
- Keep the public shape `{ reviews, aggregate, loading, error }`, the single `useEffect` keyed on
  `[productId]`, and the `cancelled` cleanup flag.
- A 404 (unknown product) must not crash the panel — surface it through the existing error state.
Constraints: plain `fetch`; no new dependency; do not touch the list path you built in Task 4.
Output: only the modified `useProductReviews.js`.

You verify

  • On a seeded product page the panel shows the average (2 decimals), the per-source averages, the full 1–5 histogram and the count — and DevTools shows :4000/api/products/<id>/aggregate returning { data: ... } with no meta.
  • It is truly live: flip one backend review’s rating from 4 to 5, reload, and the histogram and overall_avg move together (they still sum to the displayed count).
  • The backend keys overall_avg, per_source, histogram, count appear verbatim where the panel consumes them — nothing renamed.

You integrate

Warning

Negative test — required before you move on. Stop the backend again (Ctrl-C) and reload the product page: the aggregate panel must go empty/error just like the list did in Task 4. If the panel keeps rendering its numbers with your backend stopped, it is still computing from local sample data — Task 5 has not landed. Restart the backend and confirm the panel comes back.

Checkpoint. Both the list and the aggregate on a product page are served by your two routes — the required negative test above decides it. Then lock it in, from frontend/:

git add src/hooks/useProductReviews.js && git commit -m "feat(frontend): aggregate panel fetches GET /:id/aggregate (json.data)"

The empty / 404 walk (absorbed from the former optional task). From the catalog, open a real product the store never seeded (id 4): the list is empty and the aggregate panel must show the empty state built from overall_avg: null, count: 0 and all five histogram buckets at 0 — exactly what Task 3’s third curl proved the route returns. Then reach a detail page for an id the product database does not know (for example by editing the id in the URL bar): the pass condition is ProductDetail’s existing red “Product not found” panel — the 404-early rule of Tasks 2–3, now observable in the browser instead of only in curl output. No component in this course renders the reviews hook’s error: do not invent an error UI for it, and do not tick this item because the review list merely looked empty — the red panel is the observable.

Tasks 4–5 are what make the Session 3 UI render live data: the frontend calls these two routes because you wired it here — both tasks are required, not optional.

Common AI mistakes (review routes)

Mistake What to do instead
404 not early — an unknown product returns an empty list instead of 404 Confirm the product exists first (SELECT id FROM products WHERE id = ?) and return the 404 before reading the store.
Wrong envelope — the list route returns a bare array, or the aggregate route returns { data, meta } The list route returns { data, meta: { count } }; the aggregate route returns { data } (no meta).
Invented fields — a “was this useful?” flag or a product_id field on a review Keep exactly the 8 canonical fields; product_id is only a join column in Session 5’s table, never a review field.
Rating out of range — rating as 0–5 or a float rating is an integer 1–5.
Aggregation math wrong — the histogram is missing zero buckets, or per_source drops a source that is present Always emit all five keys 1..5 (even when a count is 0), and include every source that is present.
No error handling — forgetting try/catch + next(err) Wrap the async work in try/catch and forward to next(err) (no wrapper, no custom error class).
Hardcoded ids — reading a fixed product id instead of :id Read req.params.id from the route; never hardcode a product id.
Reaching for a live/external review source — S4 is in-memory only Use the in-memory store. The shipped scraper-service/ (:5000) and its POST /api/products/:id/fetch route are the S5 home stretch, not Session 4.
CORS confusion — adding cors(...) in a route, tweaking CORS, or proxying /api in vite.config.js to fix a browser request from Tasks 4–5 Change no CORS code: the app already applies cors({ origin: FRONTEND_ORIGIN, credentials: true }) in backend/src/index.js before the /api/products router is mounted, so every route you add inherits it. If a browser call fails, check your own route and URL — the router must simply stay mounted after the middleware.

Key takeaways

  • The in-memory store (backend/src/data/reviews.js) is S4’s only review data source; no new database table in S4. In S5 it is swapped for the MySQL reviews table (which adds a product_id join column) — only the two helper bodies change, never the routes.
  • 404-early — confirm the product exists before doing any work, so a missing product is an error, not a silently-empty list.
  • One envelope per route type — the list route returns { data, meta }; the aggregate route returns { data } (no meta).
  • The 8-field shape and the 1–5 integer rating are the contract — no invented flags, no product_id field, no out-of-range rating.
  • Aggregation = overall_avg + per_source (mean per source) + a 1..5 histogram (all five buckets) + count. A product with zero reviews aggregates safely: overall_avg: null, count: 0, all five histogram buckets at 0 — no NaN, no divide-by-zero.
  • The AI loop is the method: AI generates → you verify → fix what fails → commit.

Make the 404-early rule a live moment: call GET /api/products/999/aggregate and show the clean 404 { error: 'Product not found' }, then contrast it with a route that silently returns an empty list. Preview the S5 swap — the only change is the body of getProductReviews becoming a pool.query(...) on the reviews table filtered by product_id, so nothing on the frontend changes after Tasks 4–5 because the route signature and the { data } / { data, meta } envelopes stay identical.

Home stretch (1 month)

In S5 the in-memory store becomes the persistent MySQL reviews table (which adds a product_id join column, FK → products.id, on the MySQL instance at :3306). The course ships a mock scraper-service/ (Express, port :5000) that exposes review data at GET /api/scrape/reviews/:productId. In the 1-month home stretch you wire the third canonical route, POST /api/products/:id/fetch, which asks the scraper-service for a product’s reviews and stores them — that is where the “live” story begins. S4 never calls the scraper.