Open History to see the last commit
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 })
46}