homeman-deno/routes/api/todo.ts

73 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-01-07 10:55:18 -06:00
import { Handlers } from '$fresh/server.ts'
import { db, Todo, TodoModel } from '@homeman/models.ts'
import { ulid } from 'https://deno.land/x/ulid@v0.3.0/mod.ts'
2024-01-09 21:52:47 -06:00
import { z } from 'https://deno.land/x/zod@v3.21.4/mod.ts'
2024-01-07 10:55:18 -06:00
2024-01-09 21:52:47 -06:00
const TodoPayload = TodoModel.partial({ id: true }).omit({ createdAt: true })
type TodoPayload = z.infer<typeof TodoPayload>
async function createOrUpdate(todo: TodoPayload) {
if (!todo.id) {
const newTodo: Todo = { ...todo, id: ulid(), createdAt: new Date() }
return await db.todos.create({ data: newTodo })
} else {
return await db.todos.update({ where: { id: todo.id }, data: todo })
}
}
2024-01-07 10:55:18 -06:00
export const handler: Handlers<Todo | null> = {
async POST(req, _ctx) {
2024-01-09 21:52:47 -06:00
if (req.headers.get('content-type')?.includes('json')) {
const result = await createOrUpdate(TodoPayload.parse(await req.json()))
return new Response(JSON.stringify(result))
} else {
const form = await req.formData()
const id = form.get('id')?.toString()
const doneAt = form.get('doneAt')
console.log('todo POST doneAt:', doneAt)
const todo = TodoPayload.parse({
id: id,
emoji: form.get('emoji')?.toString(),
description: form.get('description')?.toString(),
assigneeUserId: form.get('assigneeUserId')?.toString(),
})
if (!id) {
delete todo.id
}
await createOrUpdate(todo)
const url = new URL(req.url)
url.pathname = '/admin'
return Response.redirect(url, 303)
}
2024-01-07 10:55:18 -06:00
},
async DELETE(req, _ctx) {
2024-01-09 21:52:47 -06:00
// TODO: form or query params or json
let data
if (req.headers.get('content-type')?.includes('json')) {
data = await req.json()
} else {
data = { id: new URL(req.url).searchParams.get('id') }
}
const todoData = TodoModel.pick({ id: true }).parse(data)
2024-01-07 10:55:18 -06:00
const result = await db.todos.delete({ where: todoData })
return new Response(JSON.stringify(result))
},
async GET(req, _ctx) {
2024-01-09 21:52:47 -06:00
// TODO: json or query params
2024-01-07 10:55:18 -06:00
const data = await req.json().catch(() => {})
const todoData = TodoModel.pick({ id: true }).safeParse(data)
if (todoData.success) {
return new Response(
JSON.stringify(await db.todos.findFirst({ where: todoData.data })),
)
} else {
return new Response(JSON.stringify(await db.todos.findMany({})))
}
},
}