Advanced Web Applications Development

Labs · Lab

Lab A — find today's fare

Make the search work: find the route, then the fare that is in effect today — not just any fare for that route.

In this lab

  • Reading query parameters, and refusing bad ones
  • Asking for the fare that is in effect today
  • Saying clearly which thing is missing
Time
35 min
Start from
main
Finish at
checkpoint/lab-a-done

The search form already works. The API behind it does not. Pressing Find the fare right now returns a 501 that tells you to open one file.

This lab is that file.

The idea

There is a route from Westfield to Brikama, and that route has two fare rows: one from September 2025, one from April 2026 when fuel went up. Asking the database for “the fare for this route” gets you both, and picking the first is a coin flip.

Today’s fare is the row with the latest effective_from that is not in the future. Everything in this lab follows from that sentence.

Note what you are not doing: you are not pasting the stop ids into a string of SQL. Prisma sends values separately from the query, so a stop id can never be read as a command. Lab B shows what happens when that stops being true.

Catch up

If you are starting here, or your copy has drifted:

git checkout main
npm run reset

Steps

1. Open the file.

code api/routes/fares.js

It currently returns the “Not built yet” message. You are replacing the body of that handler.

2. Bring in the database client. At the top of the file, under the Router import:

import { db } from '../db.js';

3. Read the two stop ids, and refuse anything that is not a number. The browser sends ?from=1&to=8, and query strings are always text. Put the guard at the top of the handler, and make the handler async while you are there — the database answers with a promise.

In the code below, the highlighted lines are the ones you add; the dimmed lines are there so you can see where they go:

router.get('/', async (req, res) => {
  const from = Number(req.query.from);
  const to = Number(req.query.to);

  if (!Number.isInteger(from) || !Number.isInteger(to)) {
    return res.status(400).json({ error: 'from and to must both be stop ids' });
  }
});

4. Find the route, and the one fare that matters. This is the heart of the lab. The where inside fares is what makes it today’s fare.

From here on, // ... stands for code that is already in the file — do not type those lines again. (// TODO:, when you meet it in Lab B, means the opposite: a line you still have to write.)

router.get('/', async (req, res) => {
  // ... the from and to guard you just wrote

  const route = await db.route.findFirst({
    where: { originId: from, destinationId: to },
    include: {
      origin: true,
      destination: true,
      fares: {
        where: { effectiveFrom: { lte: new Date() } },
        orderBy: { effectiveFrom: 'desc' },
        take: 1,
      },
    },
  });
});

Read that inner block aloud: fares that started on or before today, newest first, just one.

5. Say clearly which thing is missing. “No route” and “no fare” are different problems for whoever has to fix them:

router.get('/', async (req, res) => {
  // ... the guard and the route lookup

  if (!route) {
    return res.status(404).json({ error: 'No route between those two stops' });
  }

  const [fare] = route.fares;

  if (!fare) {
    return res.status(404).json({ error: 'No fare recorded for that route yet' });
  }
});

6. Answer in the shape the web app already expects. Open web/app.js if you want to see where each field lands on the page:

router.get('/', async (req, res) => {
  // ... the guard, the lookup, and the two 404s

  res.json({
    from: route.origin.name,
    to: route.destination.name,
    vehicleType: route.vehicleType,
    amountDalasi: fare.amountDalasi,
    effectiveFrom: fare.effectiveFrom,
    status: fare.status,
  });
});

7. Try it in the browser. The server restarts itself. Go to localhost:3000, pick Westfield and Brikama, and press Find the fare.

8. Try it from the command line. The browser is one client. Here is another, which is the whole point of having an API:

curl "localhost:3000/api/fares?from=1&to=8"

Checkpoint

The page shows D45, a SAMPLE badge, and “In effect since 2026-04-01”.

D45 is the April 2026 fare. If you see D35 you have the 2025 row, which means the orderBy or the take: 1 is not doing what you think.

The command line gives you the same answer as JSON:

{"from":"Westfield","to":"Brikama","vehicleType":"van","amountDalasi":45,"effectiveFrom":"2026-04-01T00:00:00.000Z","status":"sample"}

Two more worth trying:

curl "localhost:3000/api/fares?from=8&to=1"
curl "localhost:3000/api/fares?from=abc&to=8"

The first returns No route between those two stops with a 404 — Brikama to Westfield is a different trip and nobody has entered it. The second returns from and to must both be stop ids with a 400.

If it breaks

“Cannot read properties of undefined” — the handler is not async, or there is no await before db.route.findFirst. You are reading a promise as if it were a route.

The page says “Not built yet” — the old handler is still there. You added the new code but left the original res.status(501) above it, so it answers first.

You get D35 instead of D45 — the orderBy is missing, or it says asc.

“No route between those two stops” for every pair — check the order of originId and destinationId. A route runs one way.

Nothing at all, and the terminal shows a database error — the server lost the database. npm run setup and try again.

The finished file

api/routes/fares.js after all eight steps, as it stands on checkpoint/lab-a-done. Read it against yours rather than pasting it — if they differ and yours passes the checkpoint, yours is not wrong.

import { Router } from 'express';
import { db } from '../db.js';

const router = Router();

// GET /api/fares?from=1&to=8
//
// "What is the fare today" is not "the fare row for this route". It is the
// row with the latest effective_from that is not in the future.
router.get('/', async (req, res) => {
  const from = Number(req.query.from);
  const to = Number(req.query.to);

  if (!Number.isInteger(from) || !Number.isInteger(to)) {
    return res.status(400).json({ error: 'from and to must both be stop ids' });
  }

  const route = await db.route.findFirst({
    where: { originId: from, destinationId: to },
    include: {
      origin: true,
      destination: true,
      fares: {
        where: { effectiveFrom: { lte: new Date() } },
        orderBy: { effectiveFrom: 'desc' },
        take: 1,
      },
    },
  });

  if (!route) {
    return res.status(404).json({ error: 'No route between those two stops' });
  }

  const [fare] = route.fares;

  if (!fare) {
    return res.status(404).json({ error: 'No fare recorded for that route yet' });
  }

  res.json({
    from: route.origin.name,
    to: route.destination.name,
    vehicleType: route.vehicleType,
    amountDalasi: fare.amountDalasi,
    effectiveFrom: fare.effectiveFrom,
    status: fare.status,
  });
});

export default router;

Stretch

Finished early? Both of these are small, and both come up in real use.

  1. Show what it was before. Return the previous fare alongside today’s, so the page could say “was D35 until April”. Hint: take: 2.
  2. Say when the next one starts. A fare row dated in the future is already in the table for some routes. Return it as nextFare so a bursar can see a rise coming.

For trainers

Before you move on, three questions. Write down your answers — they are the raw material for your own version of this lab.

  1. Where would your students get stuck first?
  2. What would you cut if you had twenty minutes instead of thirty-five?
  3. What would you add that is missing here?
Saved in this browser only.