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

todos.post.ts

37 lines803 Bytes

1import type { Todo } from '../../app/services/todos/types'
2​
3export default defineEventHandler(async (event) => {
4 const body: unknown = await readBody(event).catch(() => null)
5​
6 const text =
7 body !== null &&
8 typeof body === 'object' &&
9 'text' in body &&
10 typeof body.text === 'string'
11 ? body.text.trim()
12 : ''
13​
14 if (!text) {
15 throw createError({ statusCode: 400, message: 'text is required' })
16 }
17​
18 await new Promise((resolve) => setTimeout(resolve, 500))
19​
20 if (Math.random() < 0.3) {
21 throw createError({
22 statusCode: 500,
23 message: 'Server error β€” please try again',
24 })
25 }
26​
27 const newTodo: Todo = {
28 id: crypto.randomUUID(),
29 text,
30 createdAt: Date.now(),
31 }
32​
33 todos.push(newTodo)
34​
35 setResponseStatus(event, 201)
36 return newTodo
37})