homeman-deno/routes/api/todo.ts

145 lines
4 KiB
TypeScript
Raw Normal View History

2024-01-07 10:55:18 -06:00
import { Handlers } from '$fresh/server.ts'
2024-01-17 15:10:28 -06:00
import { db, kv, Todo, TodoModel } from '@homeman/models.ts'
2024-01-07 10:55:18 -06:00
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-17 15:10:28 -06:00
const TodoPayload = TodoModel.partial({ id: true }).omit({
createdAt: true,
})
2024-01-09 21:52:47 -06:00
type TodoPayload = z.infer<typeof TodoPayload>
async function createOrUpdate(todo: TodoPayload) {
2024-01-17 15:10:28 -06:00
if (!todo.id || todo.id === '') {
2024-01-11 18:57:29 -06:00
const newTodo: Todo = {
...todo,
id: ulid(),
createdAt: new Date(),
}
2024-01-17 15:10:28 -06:00
const result = await db.todos.create({ data: newTodo })
await kv.set(['last_todo_updated'], newTodo.id)
return result
2024-01-09 21:52:47 -06:00
} else {
2024-01-17 15:10:28 -06:00
const result = await db.todos.update({ where: { id: todo.id }, data: todo })
await kv.set(['last_todo_updated'], todo.id)
return result
2024-01-09 21:52:47 -06:00
}
}
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')) {
2024-01-11 18:57:29 -06:00
const result = await createOrUpdate(
TodoPayload.parse(await req.json()),
)
2024-01-09 21:52:47 -06:00
return new Response(JSON.stringify(result))
} else {
const form = await req.formData()
2024-01-17 15:10:28 -06:00
const id = form.get('id')?.toString() || undefined
2024-01-09 21:52:47 -06:00
const doneAt = form.get('doneAt')
console.log('todo POST doneAt:', doneAt)
const todo = TodoPayload.parse({
id: id,
2024-01-11 18:57:29 -06:00
emoji: form.get('emoji')?.toString() || null,
doneAt: form.get('doneAt')?.toString() || null,
2024-01-09 21:52:47 -06:00
description: form.get('description')?.toString(),
2024-01-17 15:10:28 -06:00
assigneeUserId: form.get('assigneeUserId')?.toString() || null,
2024-01-09 21:52:47 -06:00
})
if (!id) {
delete todo.id
}
2024-01-17 15:10:28 -06:00
if (!todo.assigneeUserId) {
delete todo.id
}
2024-01-09 21:52:47 -06:00
await createOrUpdate(todo)
const url = new URL(req.url)
2024-01-11 18:57:29 -06:00
url.pathname = '/'
2024-01-09 21:52:47 -06:00
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') }
}
2024-01-16 16:45:51 -06:00
console.log('delete todo data:', data)
2024-01-09 21:52:47 -06:00
const todoData = TodoModel.pick({ id: true }).parse(data)
2024-01-07 10:55:18 -06:00
const result = await db.todos.delete({ where: todoData })
2024-01-17 15:10:28 -06:00
await kv.set(['last_todo_updated'], todoData.id)
2024-01-07 10:55:18 -06:00
return new Response(JSON.stringify(result))
},
2024-01-17 15:10:28 -06:00
async GET(req, ctx) {
2024-01-09 21:52:47 -06:00
// TODO: json or query params
2024-01-17 15:10:28 -06:00
const accept = req.headers.get('accept')
if (accept === 'text/event-stream') {
const stream = kv.watch([['last_todo_updated']]).getReader()
const body = new ReadableStream({
async start(controller) {
console.log(
`Streaming todo updates to ${JSON.stringify(ctx.remoteAddr)}...`,
)
while (true) {
try {
const entries = await stream.read()
console.log('streaming todo entries:', entries)
for (const entry of entries.value || []) {
console.log('streaming todo entry:', entry)
if (typeof entry.value !== 'string') {
console.error('Invalid last_todo_updated entry:', entry)
continue
}
const todo = await db.todos.findFirst({
where: { id: entry.value },
})
const chunk = `data: ${
JSON.stringify({
id: entry.value,
versionstamp: entry.versionstamp,
value: todo,
})
}\n\n`
controller.enqueue(new TextEncoder().encode(chunk))
}
if (entries.done) {
return
}
} catch (e) {
console.error(`Error refreshing todo:`, e)
}
}
},
cancel() {
stream.cancel()
console.log(
`Closed todo updates stream to ${JSON.stringify(ctx.remoteAddr)}`,
)
},
})
return new Response(body, {
headers: {
'content-type': 'text/event-stream',
},
})
}
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({})))
}
},
}