36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
|
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'
|
||
|
|
||
|
const TodoCreate = TodoModel.omit({ id: true, createdAt: true })
|
||
|
|
||
|
export const handler: Handlers<Todo | null> = {
|
||
|
async POST(req, _ctx) {
|
||
|
const todo = TodoCreate.parse(await req.json())
|
||
|
const newTodo: Todo = { ...todo, id: ulid(), createdAt: new Date() }
|
||
|
const result = await db.todos.create({ data: newTodo })
|
||
|
return new Response(JSON.stringify(result))
|
||
|
},
|
||
|
async PUT(req, _ctx) {
|
||
|
const todo = TodoModel.parse(await req.json())
|
||
|
const result = await db.todos.update({ data: todo })
|
||
|
return new Response(JSON.stringify(result))
|
||
|
},
|
||
|
async DELETE(req, _ctx) {
|
||
|
const todoData = TodoModel.pick({ id: true }).parse(await req.json())
|
||
|
const result = await db.todos.delete({ where: todoData })
|
||
|
return new Response(JSON.stringify(result))
|
||
|
},
|
||
|
async GET(req, _ctx) {
|
||
|
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({})))
|
||
|
}
|
||
|
},
|
||
|
}
|