Fix svelte optimistic updates example#8005
Conversation
WalkthroughIntroduces an early return in the POST error path of the Svelte route handler to stop execution after sending an error response. The success path is unchanged: create newTodo, push to items, and return 200 with the created item. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant C as Client
participant S as Svelte Server (+server.ts)
participant V as Validation/Lookup
participant D as In-memory items
C->>S: POST /api/data
S->>V: Validate/lookup request data
alt Error condition
V-->>S: Error details
S-->>C: json(error), status != 200
note over S: Early return stops further execution
else Success
V-->>S: Validated payload
S->>D: Create and push newTodo
D-->>S: newTodo
S-->>C: json(newTodo), status 200
end
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
|
View your CI Pipeline Execution ↗ for commit 178747d
☁️ Nx Cloud last updated this comment at |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
examples/svelte/optimistic-updates/src/routes/api/data/+server.ts (4)
19-23: Add minimal input validation to avoid runtime errors.Guard against missing/non-string text and return 400 early.
- const { text } = await request.json() - - if (Math.random() > 0.7) { - return json({ message: 'Could not add item!' }, { status: 500 }) - } + const body = (await request.json()) as Partial<Todo> + const text = body?.text + if (typeof text !== 'string' || !text.trim()) { + return json({ message: 'text must be a non-empty string' }, { status: 400 }) + } + + if (Math.random() > 0.7) { + return json({ message: 'Could not add item!' }, { status: 500 }) + }
25-28: Prefer stable IDs over Math.random().Use crypto UUIDs for uniqueness; drop the unnecessary cast once validated.
import { json } from '@sveltejs/kit' +import { randomUUID } from 'node:crypto'const newTodo = { - id: Math.random().toString(), - text: text.toUpperCase() as string, + id: randomUUID(), + text: text.toUpperCase(), }
30-30: Nit: use 201 for resource creation.Not required for the example, but more RESTful.
- return json(newTodo, { status: 200 }) + return json(newTodo, { status: 201 })
11-12: Remove redundant JSDoc type annotations.You already have TS types on the handlers; the JSDoc adds noise.
-/** @type {import('./$types').RequestHandler} */ export const GET: RequestHandler = async (req) => {-/** @type {import('./$types').RequestHandler} */ export const POST: RequestHandler = async ({ request }) => {Also applies to: 17-18
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
examples/svelte/optimistic-updates/src/routes/api/data/+server.ts(1 hunks)
| if (Math.random() > 0.7) { | ||
| json({ message: 'Could not add item!' }, { status: 500 }) | ||
| return json({ message: 'Could not add item!' }, { status: 500 }) | ||
| } |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Early return correctly stops success path — fix looks good.
This prevents accidental creation on simulated failures and aligns with the PR intent.
To ensure the client surfaces this error, verify the mutation code throws on non-2xx responses:
🏁 Script executed:
#!/bin/bash
# From repo root
# 1) Find calls that POST to this endpoint
rg -nP -C2 --type=ts '(fetch|POST).*?/api/data' examples/svelte/optimistic-updates || true
# 2) Check mutation logic throws on !res.ok or otherwise propagates HTTP 500
rg -nP -C3 --type=ts '(mutationFn|createMutation|useMutation).*' examples/svelte/optimistic-updates || true
rg -nP -C2 --type=ts '!res\.ok|throw\s+new\s+Error' examples/svelte/optimistic-updates || trueLength of output: 296
🏁 Script executed:
#!/bin/bash
# List all files under the example to locate relevant client code
ls -R examples/svelte/optimistic-updates/src/routes
echo "---- +page.svelte ----"
sed -n '1,200p' examples/svelte/optimistic-updates/src/routes/+page.svelte || true
echo "---- +page.ts ----"
sed -n '1,200p' examples/svelte/optimistic-updates/src/routes/+page.ts || true
echo "---- All .ts files under src/lib ----"
find examples/svelte/optimistic-updates/src/lib -type f -name '*.ts'Length of output: 4014
Add non-2xx error handling in createTodo
The createTodo function currently calls res.json() regardless of HTTP status, so 500 responses won’t throw and the mutation’s onError won’t run. In examples/svelte/optimistic-updates/src/routes/+page.svelte, update createTodo to check res.ok and throw on failure, for example:
const createTodo = async (text: string): Promise<Todo> => {
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
});
if (!res.ok) {
const { message } = await res.json();
throw new Error(message);
}
return res.json();
}🤖 Prompt for AI Agents
In examples/svelte/optimistic-updates/src/routes/+page.svelte around lines where
createTodo calls fetch (referenced by the server change at
src/routes/api/data/+server.ts lines 21-23), createTodo currently calls
res.json() unconditionally so 500 responses won't trigger onError; update
createTodo to check res.ok after the fetch, if not ok await res.json() to
extract the message and throw a new Error(message), otherwise return await
res.json() so non-2xx responses propagate as exceptions to the mutation's
onError handler.
The example is currently broken. The random error on POST does not return and so items are always accepted.
Summary by CodeRabbit