Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { json } from '@tanstack/react-start'
3import type { TodoInput } from '~/utils/todos'
4import { todoService } from '~/utils/todos'
5
6export const Route = createFileRoute(`/api/todos`)({
7 server: {
8 handlers: {
9 GET: async ({ request }) => {
10 console.info(`GET /api/todos @`, request.url)
11
12 try {
13 const todos = await todoService.withDelay(() => {
14 // Occasionally simulate failure for demo
15 todoService.simulateFailure(0.1)
16 return todoService.getAll()
17 })
18
19 return json(todos)
20 } catch (error) {
21 console.error(`Error fetching todos:`, error)
22 return json({ error: `Failed to fetch todos` }, { status: 500 })
23 }
24 },
25
26 POST: async ({ request }) => {
27 console.info(`POST /api/todos @`, request.url)
28
29 try {
30 const body = (await request.json()) as TodoInput
31
32 if (!body.text || body.text.trim() === ``) {
33 return json({ error: `Todo text is required` }, { status: 400 })
34 }
35
36 const todo = await todoService.withDelay(() => {
37 // Occasionally simulate failure for demo
38 todoService.simulateFailure(0.15)
39 return todoService.create(body)
40 })
41
42 return json(todo, { status: 201 })
43 } catch (error) {
44 console.error(`Error creating todo:`, error)
45 if (error instanceof Error && error.message.includes(`Simulated`)) {
46 return json(
47 { error: `Network error - please try again` },
48 { status: 503 },
49 )
50 }
51 return json({ error: `Failed to create todo` }, { status: 500 })
52 }
53 },
54 },
55 },
56})