Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

route.ts

46 lines1.0 KB

1import { NextResponse } from 'next/server'
2import { todos, getTodos, type Todo } from './data'
3​
4export async function GET() {
5 return NextResponse.json(await getTodos())
6}
7​
8export async function POST(request: Request) {
9 let body: unknown
10 try {
11 body = await request.json()
12 } catch {
13 return NextResponse.json({ error: 'text is required' }, { status: 400 })
14 }
15​
16 const text =
17 body !== null &&
18 typeof body === 'object' &&
19 'text' in body &&
20 typeof (body as { text: unknown }).text === 'string'
21 ? (body as { text: string }).text.trim()
22 : ''
23​
24 if (!text) {
25 return NextResponse.json({ error: 'text is required' }, { status: 400 })
26 }
27​
28 await new Promise((resolve) => setTimeout(resolve, 500))
29​
30 if (Math.random() < 0.3) {
31 return NextResponse.json(
32 { error: 'Server error β€” please try again' },
33 { status: 500 },
34 )
35 }
36​
37 const newTodo: Todo = {
38 id: crypto.randomUUID(),
39 text,
40 createdAt: Date.now(),
41 }
42​
43 todos.push(newTodo)
44​
45 return NextResponse.json(newTodo, { status: 201 })