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

fake-server.ts

294 lines10.4 KB

1import { z } from "zod";
2​
3import { accountSchema, noteSchema } from "@/db/schema";
4import type { Account, Folder, Note } from "@/db/schema";
5import type { SeedData } from "@/fixtures";
6​
7/**
8 * The "backend": an in-memory database behind a small REST API. It knows
9 * nothing about TanStack DB; `fakeFetch` puts it behind a `fetch`-like
10 * function. Like a real server it validates every write, and some writes are
11 * rejected (duplicate folder names, titles that are too long) so the app can
12 * show what happens to an optimistic change the server says no to.
13 *
14 * GET /api/folders PATCH /api/folders/:id
15 * GET /api/notes POST /api/notes
16 * GET /api/notes?folderId=… (one folder's notes)
17 * GET /api/notes/:id PATCH /api/notes/:id DELETE /api/notes/:id
18 * GET /api/account PATCH /api/account
19 *
20 * PATCH /api/live/notes/:id (the Neon Realtime simulation: answers `{ txid }`)
21 *
22 * Every write to a note is a database transaction with an id (`txid`). The
23 * server reports each one to `onCommit` with the rows it changed, which is
24 * what the simulated Realtime stream (`fake-realtime.ts`) sends to clients.
25 */
26​
27export const NOTE_TITLE_MAX_LENGTH = 100;
28export const FOLDER_NAME_MAX_LENGTH = 40;
29​
30export interface ServerRequest {
31 method: string;
32 /** Path only, e.g. `/api/notes/note-01`. */
33 path: string;
34 /** The query string's parameters, e.g. `folderId=work`. */
35 query?: URLSearchParams;
36 /** Parsed JSON body, if any. */
37 body: unknown;
39​
40export interface ServerResponse {
41 status: number;
42 /** Serialized as JSON; `undefined` means no body (204). */
43 body?: unknown;
45​
46/** Error responses look like `{ error: { code, message } }`. */
47export interface ApiErrorBody {
48 error: { code: string; message: string };
50​
51export interface FakeServer {
52 handle: (request: ServerRequest) => ServerResponse;
53 /** Every note as stored now (copies), and the last transaction they include. */
54 notesSnapshot: () => { rows: Note[]; txid: string };
56​
57/** A committed write to the notes table: its transaction id and the rows it changed. */
58export interface NotesCommit {
59 /** Like a PostgreSQL transaction id: a decimal string. */
60 txid: string;
61 changes: NoteRowChange[];
63​
64export type NoteRowChange = { type: "upsert"; row: Note } | { type: "delete"; key: string };
65​
66const folderPatchSchema = z.object({ name: z.string() }).partial();
67​
68const notePatchSchema = noteSchema
69 .pick({ folderId: true, title: true, body: true, pinned: true, deletedAt: true })
70 .partial();
71​
72const accountPatchSchema = accountSchema
73 .pick({
74 name: true,
75 email: true,
76 defaultFolderId: true,
77 sortNotesBy: true,
78 newNotesStartWith: true,
79 groupNotesByDate: true,
80 })
81 .partial();
82​
83class HttpError extends Error {
84 constructor(
85 readonly status: number,
86 readonly code: string,
87 message: string,
88 ) {
89 super(message);
90 }
92​
93const ok = (body: unknown, status = 200): ServerResponse => ({ status, body });
94const noContent = (): ServerResponse => ({ status: 204 });
95​
96function parse<T>(schema: z.ZodType<T>, body: unknown): T {
97 const result = schema.safeParse(body);
98 if (!result.success) {
99 const [issue] = result.error.issues;
100 const field = issue?.path.join(".");
101 throw new HttpError(
102 422,
103 "validation_failed",
104 field ? `${field}: ${issue?.message}` : "Invalid request body.",
105 );
106 }
107 return result.data;
109​
110export function createFakeServer(
111 seed: SeedData,
112 { onCommit }: { onCommit?: (commit: NotesCommit) => void } = {},
113): FakeServer {
114 // Structured clones, so nothing the app holds can change "server" data.
115 const folders = new Map(seed.folders.map((folder) => [folder.id, structuredClone(folder)]));
116 const notes = new Map(seed.notes.map((note) => [note.id, structuredClone(note)]));
117 let account = structuredClone(seed.account);
118 let lastTxid = 1000;
119​
120 /** Ends a note write: gives it a transaction id and reports the changed rows. */
121 function commitNotes(changes: NoteRowChange[]): string {
122 const txid = String(++lastTxid);
123 onCommit?.(structuredClone({ txid, changes }));
124 return txid;
125 }
126​
127 function patchNote(id: string, body: unknown): { note: Note; txid: string } {
128 const note = findNote(id);
129 const changes = parse(notePatchSchema, body);
130 if (changes.folderId !== undefined) assertFolderExists(changes.folderId);
131 if (changes.title !== undefined) validateTitle(changes.title);
132 const edited = changes.title !== undefined || changes.body !== undefined;
133 Object.assign(note, changes, edited ? { updatedAt: new Date().toISOString() } : {});
134 return { note, txid: commitNotes([{ type: "upsert", row: note }]) };
135 }
136​
137 function findFolder(id: string): Folder {
138 const folder = folders.get(id);
139 if (!folder) throw new HttpError(404, "not_found", "That folder doesn't exist.");
140 return folder;
141 }
142​
143 function findNote(id: string): Note {
144 const note = notes.get(id);
145 if (!note) throw new HttpError(404, "not_found", "That note doesn't exist.");
146 return note;
147 }
148​
149 function assertFolderExists(id: string) {
150 if (!folders.has(id))
151 throw new HttpError(422, "validation_failed", "That folder doesn't exist.");
152 }
153​
154 function validateTitle(title: string) {
155 if (title.length > NOTE_TITLE_MAX_LENGTH) {
156 throw new HttpError(
157 422,
158 "title_too_long",
159 `Note titles can be at most ${NOTE_TITLE_MAX_LENGTH} characters.`,
160 );
161 }
162 }
163​
164 function renameFolder(folder: Folder, rawName: string) {
165 const name = rawName.trim();
166 if (folder.role !== null) {
167 throw new HttpError(403, "forbidden", `“${folder.name}” can't be renamed.`);
168 }
169 if (name === "") throw new HttpError(422, "validation_failed", "Folder names can't be empty.");
170 if (name.length > FOLDER_NAME_MAX_LENGTH) {
171 throw new HttpError(
172 422,
173 "validation_failed",
174 `Folder names can be at most ${FOLDER_NAME_MAX_LENGTH} characters.`,
175 );
176 }
177 // #region duplicate-name
178 const taken = [...folders.values()].some(
179 (other) => other.id !== folder.id && other.name.toLowerCase() === name.toLowerCase(),
180 );
181 if (taken) {
182 throw new HttpError(409, "duplicate_name", `There's already a folder named “${name}”.`);
183 }
184 // #endregion duplicate-name
185 folder.name = name;
186 }
187​
188 const routes: Route[] = [
189 route("GET", "/api/folders", () =>
190 ok([...folders.values()].sort((a, b) => a.position - b.position)),
191 ),
192 route("GET", "/api/folders/:id", ({ id }) => ok(findFolder(id))),
193 route("PATCH", "/api/folders/:id", ({ id }, body) => {
194 const folder = findFolder(id);
195 const changes = parse(folderPatchSchema, body);
196 if (changes.name !== undefined) renameFolder(folder, changes.name);
197 return ok(folder);
198 }),
199​
200 route("GET", "/api/notes", (_params, _body, query) => {
201 const folderId = query.get("folderId");
202 const all = [...notes.values()];
203 return ok(folderId === null ? all : all.filter((note) => note.folderId === folderId));
204 }),
205 route("GET", "/api/notes/:id", ({ id }) => ok(findNote(id))),
206 route("POST", "/api/notes", (_params, body) => {
207 const note = parse(noteSchema, body);
208 if (notes.has(note.id)) {
209 throw new HttpError(409, "duplicate_id", "A note with this id already exists.");
210 }
211 assertFolderExists(note.folderId);
212 validateTitle(note.title);
213 notes.set(note.id, note);
214 commitNotes([{ type: "upsert", row: note }]);
215 return ok(note, 201);
216 }),
217 route("PATCH", "/api/notes/:id", ({ id }, body) => ok(patchNote(id, body).note)),
218 route("DELETE", "/api/notes/:id", ({ id }) => {
219 findNote(id);
220 notes.delete(id);
221 commitNotes([{ type: "delete", key: id }]);
222 return noContent();
223 }),
224 // #region live-patch-note
225 // Like an endpoint in a Neon Realtime app: it saves the change and
226 // answers with the id of the database transaction that saved it.
227 route("PATCH", "/api/live/notes/:id", ({ id }, body) => {
228 const { txid } = patchNote(id, body);
229 return ok({ txid });
230 }),
231 // #endregion live-patch-note
232​
233 route("GET", "/api/account", () => ok(account)),
234 route("PATCH", "/api/account", (_params, body) => {
235 const changes = parse(accountPatchSchema, body);
236 if (changes.defaultFolderId !== undefined) assertFolderExists(changes.defaultFolderId);
237 account = { ...account, ...changes } satisfies Account;
238 return ok(account);
239 }),
240 ];
241​
242 return {
243 notesSnapshot: () => ({ rows: structuredClone([...notes.values()]), txid: String(lastTxid) }),
244 handle({ method, path, body, query = new URLSearchParams() }) {
245 try {
246 const matches = routes
247 .map((candidate) => ({ candidate, params: matchPath(candidate.pattern, path) }))
248 .filter((match) => match.params !== null);
249 if (matches.length === 0) throw new HttpError(404, "not_found", `No route for ${path}.`);
250 const match = matches.find(({ candidate }) => candidate.method === method);
251 if (!match)
252 throw new HttpError(405, "method_not_allowed", `${method} ${path} isn't allowed.`);
253 const response = match.candidate.handler(match.params!, body, query);
254 // Responses are snapshots too.
255 return { ...response, body: structuredClone(response.body) };
256 } catch (error) {
257 if (error instanceof HttpError) {
258 return { status: error.status, body: errorBody(error.code, error.message) };
259 }
260 return { status: 500, body: errorBody("internal_error", "Something went wrong.") };
261 }
262 },
263 };
265​
266export function errorBody(code: string, message: string): ApiErrorBody {
267 return { error: { code, message } };
269​
270type Params = Record<string, string>;
271​
272interface Route {
273 method: string;
274 pattern: string;
275 handler: (params: Params, body: unknown, query: URLSearchParams) => ServerResponse;
277​
278function route(method: string, pattern: string, handler: Route["handler"]): Route {
279 return { method, pattern, handler };
281​
282/** `/api/notes/:id` matches `/api/notes/note-01` → `{ id: "note-01" }`. */
283export function matchPath(pattern: string, path: string): Params | null {
284 const patternParts = pattern.split("/");
285 const pathParts = path.split("/");
286 if (patternParts.length !== pathParts.length) return null;
287 const params: Params = {};
288 for (const [index, part] of patternParts.entries()) {
289 const value = pathParts[index]!;
290 if (part.startsWith(":")) params[part.slice(1)] = decodeURIComponent(value);
291 else if (part !== value) return null;
292 }
293 return params;