Workbench / The TiffinBox Build
S16 · V2·16
One Contract, Checked on Both Sides
Volume 2, chapter 16. The JSON the server sends gets one description, `contract/api.json`. A small generator turns it into TypeScript types and validating parsers; the frontend moves to strict TypeScript compiled under `erasableSyntaxOnly`; every response is checked before the page uses it; and a Java contract test checks the server's real responses against the same file. Renaming one field now fails three ways at once: the Java contract test, the TypeScript compile, and (if it ever reached a browser) a precise runtime error naming `Dish[][0].pricePaise`.
Stage 16: one contract, checked on both sides
The brief
What you'll build.
contract/api.json: the JSON types the server sends (Dish,OrderLine,Order,Ticket), in a deliberately small schema language:string,int(safe integer),bool,instant,enum:A|B, type names andT[];contract/gen.mjs: generatesweb-src/contract.ts: atypeand aparseX(v: unknown): Xper contract type, with error messages that give the path to the bad field;--checkfails if the committed file is stale;web-src/*.ts: the stage 15 modules rewritten in strict TypeScript, compiled toweb/*.jsbytsc;getJsonnow takes a parser, so every response is checked;ContractTest(Java): real responses from every JSON endpoint, in every order state, checked againstcontract/api.json;web-tests/contract.test.mjs(4 tests) andweb-tests/stage16.py(a server change seen from the browser);- a root
package.jsonpinning TypeScript 5.9.3.
Why a real company needs this. The most common frontend production bug in a two-language system is a field that changed on one side: renamed, made nullable, turned from a number into a string. Types written by hand on the frontend document what someone believed the API returned once. A contract that generates the frontend's types and is tested against the backend's real output turns those bugs into build failures.
Why now. Chapter 16 is TypeScript: structural types, unions, generics, declaration files, and the gap between compile-time types and run-time data. Stage 15 has exactly one API call; it's the cheapest moment to put the contract in place, before stage 17 adds live order updates.
What you'll have at the end.
- a contract with 4 types, 19 server tests (2 new), 10 JavaScript tests (4 new);
- about 7.5 KB of compiled JavaScript, no runtime dependencies;
- ADR-0018: the contract and how it changes.
Theory to own
- Types vs validation.
getJson<Dish[]>(url)withreturn res.json() as Dish[]type-checks. What does it guarantee at run time? - Where the truth lives. Three options: hand-written TypeScript types, types generated from the Java code, or a separate contract both sides are checked against. What does each make easy, and what can go wrong?
- Erasable TypeScript. What does
erasableSyntaxOnlyforbid, and why does it matter for a project with no bundler? - Strictness. Which options beyond
strictshould a new project turn on, and what does each catch? (Chapter Exercises P1.) - Compatibility. The server adds a field
veg: booltoDish. Is that a breaking change for the browser? For an old mobile app? What about renaming a field?
Build it
Step 1: the contract and its generator
Write contract/api.json from what the server actually sends today (curl each endpoint):
{
"Dish": { "id": "string", "name": "string", "pricePaise": "int" },
"OrderLine": { "dishId": "string", "quantity": "int" },
"Order": {
"id": "string", "kitchenId": "string",
"status": "enum:Placed|Accepted|Ready|Delivered|Cancelled|RefundDue",
"at": "instant", "totalPaise": "int", "lines": "OrderLine[]",
"discountPaise": "int", "payablePaise": "int", "freeDelivery": "bool", "pricedBy": "string"
},
"Ticket": { "orderId": "string", "promisedAt": "instant" }
}
Then write contract/gen.mjs: for each type, emit a readonly TypeScript type and a parseX(v: unknown, path) that checks every field and builds a new object from the declared fields only. Small helpers (str, int, bool, instant, oneOf, arr) throw a ContractError with the path. Add --check mode for CI.
Checkpoint. node contract/gen.mjs writes web-src/contract.ts; --check passes on an unchanged contract.
Step 2: TypeScript sources, strict and erasable
Move web/lib.js and web/search.js to web-src/*.ts. Write web-src/tsconfig.json with strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes, noImplicitOverride, verbatimModuleSyntax, erasableSyntaxOnly, isolatedModules, skipLibCheck: false, noEmitOnError, and outDir: "../web". Give getJson a parser parameter: getJson<T>(url, parse: (body: unknown) => T, opts). Type the DOM lookups (querySelector<HTMLInputElement>). Add a root package.json with typescript pinned to 5.9.3, and put node contract/gen.mjs --check and npx tsc -p web-src at the top of check-js.sh.
Checkpoint. tsc compiles with no errors; the stage 15 unit tests still pass against the compiled web/lib.js.
Step 3: test the generated validators
Write web-tests/contract.test.mjs: a valid list passes unchanged; a renamed field fails with Dish[][0].pricePaise: expected a safe integer, got undefined; 89.5 and 2**53 are rejected; an unknown status, a non-ISO instant, and a line without quantity each fail with their path.
Checkpoint. 4 new tests pass (10 in all).
Step 4: check the server against the same file
Write ContractTest in the server tests. Read contract/api.json with a small JSON reader (in the test; the server has no JSON parser and doesn't need one). Call every JSON endpoint: search with a query and blank, place an order that gets a discount and one that gets nothing, get an order, get a kitchen's next ticket, then move the order through accept, ready and cancel, checking the order after each. Check field names exactly (missing or extra fields fail) and types (int must be a safe integer, instant must parse and end in Z). Add a test that the checker itself rejects wrong shapes.
Checkpoint. 19 server tests pass. Then rename pricePaise in Json.java, rebuild, and read the failures; rename it in contract/api.json, regenerate, and compile the TypeScript. Undo both.
Step 5: the same failure, seen from a browser
Write web-tests/stage16.py: search for "dosa" as served, then again with the search response replaced (via page.route) by [{"id":"d1","name":"Masala dosa","price":8950}], as if a server change had shipped first. Re-run stage15.py and stage14.py.
Checkpoint. The served search works; the changed response shows the "isn't available" message, leaves the list intact, and logs a ContractError naming the field.
Senior and architect lens
1. The contract is the API; code on both sides implements it. Neither the Java classes nor the TypeScript types are the source of truth; a small, reviewed file is. That inverts the usual drift: instead of documentation trying to keep up with code, code is tested against the documentation.
2. ADR-0018: the API contract. Write it with these points:
- Decision:
contract/api.jsondescribes every JSON response; TypeScript types and parsers are generated from it; the server is tested against it on every build. - Rules: clients ignore unknown fields; the server's contract test rejects them; additions are compatible, renames and type changes aren't (add, migrate, then remove); money is integer paise, times are UTC instants, ids are strings.
- Tooling: a 50-line generator with no dependencies;
--checkin CI so generated files can't go stale. - Revisit when: the API needs optional fields, unions or request bodies in JSON (stage 30, with the contract as a workspace package), or a third consumer appears (then consider OpenAPI and standard generators).
3. Types are claims; parsers are evidence. A function that returns T after checking turns a run-time fact into a compile-time one. Everything downstream can trust the type, because there's exactly one way in (the Companion's Explain it differently 1: hire the guard at the door).
4. Erasable TypeScript keeps options open. With erasableSyntaxOnly, the compiled JavaScript is the source minus annotations: readable in the browser's debugger without source maps, and producible by any tool. Stage 30 can switch to a faster transpiler, or to no build step at all, without touching the code.
5. Contract tests catch the bugs integration tests miss. healthAndSearch compared one response to a fixed string; the contract test checks every endpoint in every state against rules. The second scales: adding a field to the contract tightens every check at once.
What breaks first, and when it's addressed:
| Pressure | What breaks | Where it's addressed |
|---|---|---|
| optional fields and unions (a cancelled order has a reason; others don't) | the schema language has neither | stage 30 (extend it, or move to OpenAPI, as a shared package) |
| live updates push orders to the browser | parsers exist only for fetch responses |
stage 17 (the same parsers for event-stream messages) |
pricedBy packs two rule names into one string |
the contract can only say "string" | stage 30 (API cleanup: two fields) |
| a mobile client appears with its own release cycle | no versioning policy beyond "additions are safe" | Volume 3 (API versioning and deprecation) |
| more TypeScript, more modules | tsc over one folder, no project references |
stage 30 (workspace builds) |
Evidence
contract/api.json,contract/gen.mjsand the generatedweb-src/contract.tsare committed;node contract/gen.mjs --checkpasses.check-js.sh: TypeScript compiles under the strict options; 10 JavaScript tests pass.- Server: 19 tests pass, including
ContractTest; the rename mutation's output (Java and TypeScript) is in the README. stage16.py's output, showing theContractErrorpath, is in the README;stage15.pyandstage14.pystill pass.- ADR-0018 is committed.
Carry forward
- Every response goes through a generated parser from now on; stage 17's live order updates use
parseOrder. contract/api.jsonchanges with the API, in the same pull request; reviewers read it first.web-src/is the frontend's source,web/its compiled output; stage 30 adds bundling and hashed file names on top.- The schema language grows in stage 30 (optional fields, unions), or is replaced by OpenAPI when a second client arrives.