Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

fake-fetch.ts

85 lines3.1 KB

1import { createSeedData } from "@/fixtures";
2import type { SeedData } from "@/fixtures";
3​
4import { createFakeServer, errorBody } from "./fake-server";
5import { getNetworkConfig, 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. The app only ever talks to the API
12 * through this, so swapping it for `window.fetch` would be the only change
13 * needed against a real backend.
14 */
15export async function fakeFetch(url: string, init: RequestInit = {}): Promise<Response> {
16 const method = (init.method ?? "GET").toUpperCase();
17 const { pathname, search } = new URL(url, "https://notes.example");
18 const body = parseJsonBody(init.body);
19 const logId = logRequestStart({ method, url: pathname + search, requestBody: body.value });
20​
21 try {
22 await delay(getNetworkConfig().latencyMs, init.signal);
23 } catch (error) {
24 logRequestEnd(logId, {
25 state: "aborted",
26 status: null,
27 responseBody: null,
28 injectedFailure: false,
29 });
30 throw error;
31 }
32​
33 const injectedFailure = takeInjectedFailure();
34 const response = injectedFailure
35 ? { status: 500, body: errorBody("injected_failure", "The server failed (on purpose).") }
36 : !body.ok
37 ? { status: 400, body: errorBody("invalid_json", "The request body isn't valid JSON.") }
38 : server.handle({ method, path: pathname, body: body.value });
39​
40 logRequestEnd(logId, {
41 state: "done",
42 status: response.status,
43 responseBody: response.body ?? null,
44 injectedFailure,
45 });
46​
47 return new Response(response.body === undefined ? null : JSON.stringify(response.body), {
48 status: response.status,
49 headers: response.body === undefined ? undefined : { "Content-Type": "application/json" },
50 });
52​
53/** The request body as JSON; a body that isn't (`ok: false`) is logged as sent and gets a 400. */
54function parseJsonBody(body: RequestInit["body"]): { ok: boolean; value: unknown } {
55 if (body === undefined || body === null) return { ok: true, value: undefined };
56 // Only JSON strings are supported; anything else (FormData, Blob…) is a bad request.
57 if (typeof body !== "string") return { ok: false, value: Object.prototype.toString.call(body) };
58 try {
59 return { ok: true, value: JSON.parse(body) };
60 } catch {
61 return { ok: false, value: body };
62 }
64​
65let server = createFakeServer(createSeedData());
66​
67/** Starts the server over with fresh data (tests; a page reload does the same). */
68export function resetFakeServer(seed: SeedData = createSeedData()) {
69 server = createFakeServer(seed);
71​
72function delay(ms: number, signal: AbortSignal | null | undefined): Promise<void> {
73 return new Promise((resolve, reject) => {
74 if (signal?.aborted) return reject(signal.reason);
75 const timer = setTimeout(() => {
76 signal?.removeEventListener("abort", onAbort);
77 resolve();
78 }, ms);
79 function onAbort() {
80 clearTimeout(timer);
81 reject(signal!.reason);
82 }
83 signal?.addEventListener("abort", onAbort, { once: true });
84 });