Contents Lesson 5 of 18

11 min read · practitioner

Pull the data layer out of the watchlist

By the end of this lesson you will have a src/lib/market.ts that the watchlist and the screen both fetch through, a watchlist unchanged against a screenshot and npm test, and two commits that change structure and nothing else.

The first real refactor. Your watchlist fetches quotes; your screener fetches screens. Both go through the proxy, both handle failure, both validate what comes back. Right now that logic lives inside the watchlist, and you are about to need it twice.

Have the checklist open before you start

You are about to accept generated code that moves working software around. Course 1 gave you four questions for a diff; this unit needs them running the whole time, so here they are as a card to keep open — worst consequence first:

  1. Leaks. Does this touch the key, the proxy, or anything a caller can influence?
  2. Cost. How many API calls does this path make, and did that number change?
  3. Lies. Is every number still in the units and currency it claims?
  4. Failure. What does this do with no data, bad data, or a dead upstream?

Unit 3 turns each of those into a lesson and shows what they catch. You do not have to wait for that to use them — a checklist you run badly beats one you read later.

The rule that decides what moves

Not "move the shared code". That instruction is too vague to act on and produces a utils.ts nobody can navigate.

The useful rule: move what would be identical in a product that has nothing to do with watchlists. Fetching through the proxy, checking res.ok, applying a timeout, narrowing an unknown response to a validated shape — none of that knows what a watchlist is. It moves.

Deciding which columns to show, what "your list" means, how a threshold rule reads — all of that is the watchlist being itself. It stays.

src/lib/
  market.ts        ← moved out: proxy fetch, ok check, timeout, shape guard
  quotes.ts        ← watchlist: turns market data into Quote rows
  screens.ts       ← new: turns market data into screen results

Three files where there was one, and the middle one got smaller. That is what a good extraction looks like: the thing you pulled out is boring, and both callers shrank.

Do it as a refactor, not a rewrite

There is a specific way to ask for this that gets a good result, and a specific way that gets a mess. Here is the shape of the good one; the exact prompt to paste is under Try it now.

Extract the proxy fetch, the res.ok check and the shape validation from src/lib/quotes.ts into a new src/lib/market.ts (the timeout already lives inside eodhdFetch and stays there). Do not change behaviour. quotes.ts keeps its exported signature exactly as it is, and calls into the new module. Show me the diff before writing.

Three constraints in there, and each one prevents a specific failure. Do not change behaviour stops opportunistic "improvements" riding along in a diff you are reading for structure. Keeps its exported signature means the watchlist page needs no edit, so if the page breaks you know the extraction is wrong. Show me the diff is the loop.

Compare with "refactor the data layer to be reusable", which invites a redesign you did not ask for and cannot review.

Verify by reverting your attention

The whole point of a behaviour-preserving refactor is that you can check it without reading it: load the watchlist and confirm nothing changed. Same rows, same numbers, same errors when you break the key.

If anything looks different, the refactor is wrong, and it is wrong now while the diff is one commit old rather than in three weeks when it is buried. This is the cheapest test you will ever run and the one people skip because the code "obviously" still works.

Commit before you build on it

git status   # src/lib/market.ts and src/lib/quotes.ts, nothing else
git add -A
git commit -m "Extract the transport out of quotes - the screener needs the same thing"

One commit that changes structure and nothing else. When the screener turns out to need a change in market.ts next week, you want that diff to sit on top of a clean extraction, not tangled inside it. This is what makes the history useful rather than archaeological.

Try it now

Do the extraction with the prompt below, then run the verification honestly: open the watchlist and compare it against a screenshot you take first. Most people skip the screenshot and then cannot say whether the third column always looked like that. Take the screenshot. With the wrong key in .env.local and mock mode off, reload each page once now and write down the failure message each shows, so that "the same as before" is something you can compare. Put the right key back. Then run npm test before and after the extraction. If the screenshot shows something no test covers, ask your agent for a test of it as a separate commit after the extraction: a refactor is the cheapest moment to pin behaviour down, but the extraction itself stays free of new tests so its numbers can be compared.

The prompt

Mock mode on, screenshot taken, plan mode on, and paste:

Extract the fetch-check-narrow steps of src/lib/quotes.ts into one
exported function, marketGet, in a new src/lib/market.ts: call
eodhdFetch, check the status before parsing,
narrow the JSON with a guard the caller passes in, and turn a throw
into a failure. On a non-ok answer keep the body if it parses: the
screener's errors are in it. Behaviour unchanged; quotes.ts keeps its
exported signatures and calls market.ts. Change no other file, add no
request, and add no test in this step. Run npm test before and after, plus typecheck, lint and
check:leak, and show me the diff before committing.

Once that is committed: "Now move src/lib/screens.ts onto market.ts the same way, same checks, diff first."

The timeout already lives inside eodhdFetch and stays there. A good answer touches market.ts and quotes.ts in the first commit, only screens.ts in the second, and no page.

Check it yourself

  1. npm test passes before and after, with the same number of tests (any new test you asked for comes in its own commit afterwards).
  2. In mock mode the watchlist matches your screenshot: same rows, numbers and order.
  3. The first commit's git diff --stat names only src/lib/market.ts and src/lib/quotes.ts.
  4. Mock mode off, the same wrong key in .env.local, one reload of each page: the same failure message you wrote down before the extraction. Put the key back.
Compare with ours
// src/lib/market.ts: nothing in here knows what a watchlist is
export async function marketGet<T>(
  path: string,
  params: Record<string, string>,
  narrow: (body: unknown) => T,
): Promise<{ ok: true; value: T } | { ok: false; status: number | null; body: unknown }> {
  try {
    const res = await eodhdFetch(path, params);  // key, timeout, mock mode
    if (!res.ok) {
      // The status says which failure; the body may not even be JSON.
      return { ok: false, status: res.status, body: await res.json().catch(() => null) };
    }
    return { ok: true, value: narrow(await res.json()) };
  } catch {
    return { ok: false, status: null, body: null };  // network, timeout, not JSON
  }
}

The full state at the end of this unit is on the starter's branch ref/build-a-screener/u2.

Checkpoint

# after the first step: market.ts and quotes.ts
npm test && npm run typecheck
git status   # only the files this step touched, no .env*
git add -A
git commit -m "Extract the transport out of quotes - the screener needs the same thing"
# after the second step: screens.ts on market.ts
npm test && npm run typecheck
git add -A
git commit -m "Screens fetch through market.ts as well"

Then answer this lesson's questions.