homeman-deno/routes/api/tasks.ts

126 lines
3.4 KiB
TypeScript
Raw Permalink Normal View History

2024-01-21 14:02:10 -06:00
import { Handlers } from '$fresh/server.ts'
2024-01-21 14:23:45 -06:00
import { Task, TaskModel } from '@homeman/models.ts'
2024-01-21 15:52:46 -06:00
import { kv } from '@homeman/db.ts'
2024-01-21 14:23:45 -06:00
import { ulid } from 'https://deno.land/x/ulid@v0.3.0/mod.ts'
2024-01-21 14:02:10 -06:00
import { z } from 'https://deno.land/x/zod@v3.21.4/mod.ts'
2024-01-21 20:10:46 -06:00
const TaskPayload = TaskModel.omit({ doneAt: true }).partial({
id: true,
}).extend({
done: z.boolean().optional(),
})
2024-01-21 14:23:45 -06:00
type TaskPayload = z.infer<typeof TaskPayload>
2024-01-21 14:02:10 -06:00
2024-01-21 14:23:45 -06:00
async function createOrUpdate(task: TaskPayload) {
2024-01-21 20:10:46 -06:00
const newTask: Task = TaskModel.parse({
...task,
doneAt: task.done ? new Date() : null,
})
if (!newTask.id || newTask.id === '') {
newTask.id = ulid()
2024-01-21 14:23:45 -06:00
}
2024-01-21 20:10:46 -06:00
const result = await kv.set(['task', newTask.id], newTask)
await kv.set(['last_task_updated'], newTask.id)
return result
2024-01-21 14:23:45 -06:00
}
export const handler: Handlers<Task | null> = {
2024-01-21 14:02:10 -06:00
async POST(req, _ctx) {
2024-01-21 20:10:46 -06:00
const result = await createOrUpdate(
TaskPayload.parse(await req.json()),
)
return new Response(JSON.stringify(result))
2024-01-21 14:02:10 -06:00
},
2024-01-21 18:11:25 -06:00
async PUT(req, _ctx) {
2024-01-21 20:10:46 -06:00
const t = TaskPayload.parse(await req.json())
const result = await createOrUpdate(t)
return new Response(JSON.stringify(result))
2024-01-21 18:11:25 -06:00
},
2024-01-21 14:02:10 -06:00
async DELETE(req, _ctx) {
2024-01-21 14:23:45 -06:00
// task: form or query params or json
let data
2024-01-21 14:02:10 -06:00
if (req.headers.get('content-type')?.includes('json')) {
2024-01-21 14:23:45 -06:00
data = await req.json()
2024-01-21 14:02:10 -06:00
} else {
2024-01-21 14:23:45 -06:00
data = { id: new URL(req.url).searchParams.get('id') }
2024-01-21 14:02:10 -06:00
}
2024-01-21 14:23:45 -06:00
console.log('delete task data:', data)
const taskData = TaskModel.pick({ id: true }).parse(data)
2024-01-21 18:11:25 -06:00
const result = await kv.delete(['task', taskData.id])
2024-01-21 14:23:45 -06:00
await kv.set(['last_task_updated'], taskData.id)
return new Response(JSON.stringify(result))
2024-01-21 14:02:10 -06:00
},
async GET(req, ctx) {
2024-01-21 14:23:45 -06:00
// task: json or query params
2024-01-21 14:02:10 -06:00
const accept = req.headers.get('accept')
if (accept === 'text/event-stream') {
console.log('Request for task event stream')
let skipFirst = true
const stream = kv.watch([['last_task_updated']]).getReader()
const body = new ReadableStream({
async start(controller) {
console.log(
`Streaming task updates to ${JSON.stringify(ctx.remoteAddr)}...`,
)
while (true) {
try {
const entries = await stream.read()
for (const entry of entries.value || []) {
if (skipFirst) {
skipFirst = false
continue
}
if (typeof entry.value !== 'string') {
continue
}
2024-01-21 18:11:25 -06:00
const task = (await kv.get(['task', entry.value])).value
2024-01-21 14:02:10 -06:00
const chunk = `data: ${
JSON.stringify({
id: entry.value,
versionstamp: entry.versionstamp,
value: task,
})
}\n\n`
2024-01-21 14:23:45 -06:00
console.log('task event chunk:', chunk)
2024-01-21 14:02:10 -06:00
controller.enqueue(new TextEncoder().encode(chunk))
}
if (entries.done) {
return
}
} catch (e) {
2024-01-21 14:23:45 -06:00
console.error(`Error refreshing task:`, e)
2024-01-21 14:02:10 -06:00
}
}
},
cancel() {
stream.cancel()
console.log(
2024-01-21 14:23:45 -06:00
`Closed task updates stream to ${JSON.stringify(ctx.remoteAddr)}`,
2024-01-21 14:02:10 -06:00
)
},
})
return new Response(body, {
headers: {
'content-type': 'text/event-stream',
},
})
}
2024-01-21 14:23:45 -06:00
const data = await req.json().catch(() => {})
const taskData = TaskModel.pick({ id: true }).safeParse(data)
if (taskData.success) {
return new Response(
2024-01-21 18:11:25 -06:00
JSON.stringify((await kv.get(['task', taskData.data.id])).value),
2024-01-21 14:23:45 -06:00
)
} else {
2024-01-21 18:11:25 -06:00
return new Response(
2024-01-21 21:03:00 -06:00
JSON.stringify(
(await Array.fromAsync(kv.list({ prefix: ['task'] }))).map((r) =>
r.value
),
),
2024-01-21 18:11:25 -06:00
)
2024-01-21 14:23:45 -06:00
}
2024-01-21 14:02:10 -06:00
},
}