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

route.ts

47 lines1.0 KB

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