Open History to see the last commit
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
21export const NOTE_TITLE_MAX_LENGTH = 100;
22export const FOLDER_NAME_MAX_LENGTH = 40;
23
24export interface ServerRequest {
25 method: string;
26 /** Path only, e.g. `/api/notes/note-01`. */
27 path: string;
28 /** The query string's parameters, e.g. `folderId=work`. */
29 query?: URLSearchParams;
30 /** Parsed JSON body, if any. */
31 body: unknown;
32}
33
34export interface ServerResponse {
35 status: number;
36 /** Serialized as JSON; `undefined` means no body (204). */
37 body?: unknown;
38}
39
40/** Error responses look like `{ error: { code, message } }`. */
41export interface ApiErrorBody {
42 error: { code: string; message: string };
43}
44
45export interface FakeServer {
46 handle: (request: ServerRequest) => ServerResponse;
47}
48
49const folderPatchSchema = z.object({ name: z.string() }).partial();
50
51const notePatchSchema = noteSchema
52 .pick({ folderId: true, title: true, body: true, pinned: true, deletedAt: true })
53 .partial();
54
55const accountPatchSchema = accountSchema
56 .pick({
57 name: true,
58 email: true,
59 defaultFolderId: true,
60 sortNotesBy: true,
61 newNotesStartWith: true,
62 groupNotesByDate: true,
63 })
64 .partial();
65
66class HttpError extends Error {
67 constructor(
68 readonly status: number,
69 readonly code: string,
70 message: string,
71 ) {
72 super(message);
73 }
74}
75
76const ok = (body: unknown, status = 200): ServerResponse => ({ status, body });
77const noContent = (): ServerResponse => ({ status: 204 });
78
79function parse<T>(schema: z.ZodType<T>, body: unknown): T {
80 const result = schema.safeParse(body);
81 if (!result.success) {
82 const [issue] = result.error.issues;
83 const field = issue?.path.join(".");
84 throw new HttpError(
85 422,
86 "validation_failed",
87 field ? `${field}: ${issue?.message}` : "Invalid request body.",
88 );
89 }
90 return result.data;
91}
92
93export function createFakeServer(seed: SeedData): FakeServer {
94 // Structured clones, so nothing the app holds can change "server" data.
95 const folders = new Map(seed.folders.map((folder) => [folder.id, structuredClone(folder)]));
96 const notes = new Map(seed.notes.map((note) => [note.id, structuredClone(note)]));
97 let account = structuredClone(seed.account);
98
99 function findFolder(id: string): Folder {
100 const folder = folders.get(id);
101 if (!folder) throw new HttpError(404, "not_found", "That folder doesn't exist.");
102 return folder;
103 }
104
105 function findNote(id: string): Note {
106 const note = notes.get(id);
107 if (!note) throw new HttpError(404, "not_found", "That note doesn't exist.");
108 return note;
109 }
110
111 function assertFolderExists(id: string) {
112 if (!folders.has(id))
113 throw new HttpError(422, "validation_failed", "That folder doesn't exist.");
114 }
115
116 function validateTitle(title: string) {
117 if (title.length > NOTE_TITLE_MAX_LENGTH) {
118 throw new HttpError(
119 422,
120 "title_too_long",
121 `Note titles can be at most ${NOTE_TITLE_MAX_LENGTH} characters.`,
122 );
123 }
124 }
125
126 function renameFolder(folder: Folder, rawName: string) {
127 const name = rawName.trim();
128 if (folder.role !== null) {
129 throw new HttpError(403, "forbidden", `“${folder.name}” can't be renamed.`);
130 }
131 if (name === "") throw new HttpError(422, "validation_failed", "Folder names can't be empty.");
132 if (name.length > FOLDER_NAME_MAX_LENGTH) {
133 throw new HttpError(
134 422,
135 "validation_failed",
136 `Folder names can be at most ${FOLDER_NAME_MAX_LENGTH} characters.`,
137 );
138 }
139 // #region duplicate-name
140 const taken = [...folders.values()].some(
141 (other) => other.id !== folder.id && other.name.toLowerCase() === name.toLowerCase(),
142 );
143 if (taken) {
144 throw new HttpError(409, "duplicate_name", `There's already a folder named “${name}”.`);
145 }
146 // #endregion duplicate-name
147 folder.name = name;
148 }
149
150 const routes: Route[] = [
151 route("GET", "/api/folders", () =>
152 ok([...folders.values()].sort((a, b) => a.position - b.position)),
153 ),
154 route("GET", "/api/folders/:id", ({ id }) => ok(findFolder(id))),
155 route("PATCH", "/api/folders/:id", ({ id }, body) => {
156 const folder = findFolder(id);
157 const changes = parse(folderPatchSchema, body);
158 if (changes.name !== undefined) renameFolder(folder, changes.name);
159 return ok(folder);
160 }),
161
162 route("GET", "/api/notes", (_params, _body, query) => {
163 const folderId = query.get("folderId");
164 const all = [...notes.values()];
165 return ok(folderId === null ? all : all.filter((note) => note.folderId === folderId));
166 }),
167 route("GET", "/api/notes/:id", ({ id }) => ok(findNote(id))),
168 route("POST", "/api/notes", (_params, body) => {
169 const note = parse(noteSchema, body);
170 if (notes.has(note.id)) {
171 throw new HttpError(409, "duplicate_id", "A note with this id already exists.");
172 }
173 assertFolderExists(note.folderId);
174 validateTitle(note.title);
175 notes.set(note.id, note);
176 return ok(note, 201);
177 }),
178 route("PATCH", "/api/notes/:id", ({ id }, body) => {
179 const note = findNote(id);
180 const changes = parse(notePatchSchema, body);
181 if (changes.folderId !== undefined) assertFolderExists(changes.folderId);
182 if (changes.title !== undefined) validateTitle(changes.title);
183 const edited = changes.title !== undefined || changes.body !== undefined;
184 Object.assign(note, changes, edited ? { updatedAt: new Date().toISOString() } : {});
185 return ok(note);
186 }),
187 route("DELETE", "/api/notes/:id", ({ id }) => {
188 findNote(id);
189 notes.delete(id);
190 return noContent();
191 }),
192
193 route("GET", "/api/account", () => ok(account)),
194 route("PATCH", "/api/account", (_params, body) => {
195 const changes = parse(accountPatchSchema, body);
196 if (changes.defaultFolderId !== undefined) assertFolderExists(changes.defaultFolderId);
197 account = { ...account, ...changes } satisfies Account;
198 return ok(account);
199 }),
200 ];
201
202 return {
203 handle({ method, path, body, query = new URLSearchParams() }) {
204 try {
205 const matches = routes
206 .map((candidate) => ({ candidate, params: matchPath(candidate.pattern, path) }))
207 .filter((match) => match.params !== null);
208 if (matches.length === 0) throw new HttpError(404, "not_found", `No route for ${path}.`);
209 const match = matches.find(({ candidate }) => candidate.method === method);
210 if (!match)
211 throw new HttpError(405, "method_not_allowed", `${method} ${path} isn't allowed.`);
212 const response = match.candidate.handler(match.params!, body, query);
213 // Responses are snapshots too.
214 return { ...response, body: structuredClone(response.body) };
215 } catch (error) {
216 if (error instanceof HttpError) {
217 return { status: error.status, body: errorBody(error.code, error.message) };
218 }
219 return { status: 500, body: errorBody("internal_error", "Something went wrong.") };
220 }
221 },
222 };
223}
224
225export function errorBody(code: string, message: string): ApiErrorBody {
226 return { error: { code, message } };
227}
228
229type Params = Record<string, string>;
230
231interface Route {
232 method: string;
233 pattern: string;
234 handler: (params: Params, body: unknown, query: URLSearchParams) => ServerResponse;
235}
236
237function route(method: string, pattern: string, handler: Route["handler"]): Route {
238 return { method, pattern, handler };
239}
240
241/** `/api/notes/:id` matches `/api/notes/note-01` → `{ id: "note-01" }`. */
242export function matchPath(pattern: string, path: string): Params | null {
243 const patternParts = pattern.split("/");
244 const pathParts = path.split("/");
245 if (patternParts.length !== pathParts.length) return null;
246 const params: Params = {};
247 for (const [index, part] of patternParts.entries()) {
248 const value = pathParts[index]!;
249 if (part.startsWith(":")) params[part.slice(1)] = decodeURIComponent(value);
250 else if (part !== value) return null;
251 }
252 return params;
253}