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' import { z } from 'https://deno.land/x/zod@v3.21.4/mod.ts' const TodoPayload = TodoModel.partial({ id: true }).omit({ createdAt: true }) type TodoPayload = z.infer 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 }) } } export const handler: Handlers = { async POST(req, _ctx) { 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) } }, async DELETE(req, _ctx) { // 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) const result = await db.todos.delete({ where: todoData }) return new Response(JSON.stringify(result)) }, async GET(req, _ctx) { // TODO: json or query params 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({}))) } }, }