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