Open History to see the last commit
1import { createSeedData } from "@/fixtures";
2import type { SeedData } from "@/fixtures";
3
4import { createFakeServer, errorBody } from "./fake-server";
5import { getNetworkConfig, setNetworkConfig, takeInjectedFailure } from "./network-config";
6import { logRequestEnd, logRequestStart } from "./request-log";
7
8/**
9 * `fetch`, but the "network" is a function call into the in-memory server.
10 * Every request waits for the configured latency, may fail on purpose, and
11 * is recorded in the request log. Whether it fails on purpose is decided
12 * when it's sent: turning on "fail next request" doesn't touch a request
13 * that's already in flight, and the one it does catch still takes the
14 * latency to fail. The app only ever talks to the API
15 * through this, so swapping it for `window.fetch` would be the only change
16 * needed against a real backend.
17 */
18export async function fakeFetch(url: string, init: RequestInit = {}): Promise<Response> {
19 const method = (init.method ?? "GET").toUpperCase();
20 const { pathname, search, searchParams } = new URL(url, "https://notes.example");
21 const body = parseJsonBody(init.body);
22 const { latencyMs, failNextRequest } = getNetworkConfig();
23 const injectedFailure = takeInjectedFailure();
24 const logId = logRequestStart({
25 method,
26 url: pathname + search,
27 requestBody: body.value,
28 latencyMs,
29 });
30
31 try {
32 await delay(latencyMs, init.signal);
33 } catch (error) {
34 // Never answered: "fail next request" is still waiting for a request to fail.
35 if (injectedFailure && failNextRequest) setNetworkConfig({ failNextRequest: true });
36 logRequestEnd(logId, {
37 state: "aborted",
38 status: null,
39 responseBody: null,
40 injectedFailure: false,
41 });
42 throw error;
43 }
44
45 const response = injectedFailure
46 ? { status: 500, body: errorBody("injected_failure", "The server failed (on purpose).") }
47 : !body.ok
48 ? { status: 400, body: errorBody("invalid_json", "The request body isn't valid JSON.") }
49 : server.handle({ method, path: pathname, query: searchParams, body: body.value });
50
51 logRequestEnd(logId, {
52 state: "done",
53 status: response.status,
54 responseBody: response.body ?? null,
55 injectedFailure,
56 });
57
58 return new Response(response.body === undefined ? null : JSON.stringify(response.body), {
59 status: response.status,
60 headers: response.body === undefined ? undefined : { "Content-Type": "application/json" },
61 });
62}
63
64/** The request body as JSON; a body that isn't (`ok: false`) is logged as sent and gets a 400. */
65function parseJsonBody(body: RequestInit["body"]): { ok: boolean; value: unknown } {
66 if (body === undefined || body === null) return { ok: true, value: undefined };
67 // Only JSON strings are supported; anything else (FormData, Blob…) is a bad request.
68 if (typeof body !== "string") return { ok: false, value: Object.prototype.toString.call(body) };
69 try {
70 return { ok: true, value: JSON.parse(body) };
71 } catch {
72 return { ok: false, value: body };
73 }
74}
75
76let server = createFakeServer(createSeedData());
77
78/** Starts the server over with fresh data (tests; a page reload does the same). */
79export function resetFakeServer(seed: SeedData = createSeedData()) {
80 server = createFakeServer(seed);
81}
82
83function delay(ms: number, signal: AbortSignal | null | undefined): Promise<void> {
84 return new Promise((resolve, reject) => {
85 if (signal?.aborted) return reject(signal.reason);
86 const timer = setTimeout(() => {
87 signal?.removeEventListener("abort", onAbort);
88 resolve();
89 }, ms);
90 function onAbort() {
91 clearTimeout(timer);
92 reject(signal!.reason);
93 }
94 signal?.addEventListener("abort", onAbort, { once: true });
95 });
96}