homeman-deno/routes/api/user.ts
2024-01-27 14:31:03 -06:00

145 lines
4.2 KiB
TypeScript

import { Handlers } from '$fresh/server.ts'
import { User, UserModel } from '@homeman/models.ts'
import { db, kv } from '@homeman/db.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 UserPayload = UserModel.partial({ id: true }).omit({ createdAt: true })
type UserPayload = z.infer<typeof UserPayload>
async function createOrUpdate(user: UserPayload) {
if (user.color && user.color[0] == '#') {
user.color = user.color.substring(1)
}
if (!user.id) {
const newUser: User = { ...user, id: ulid(), createdAt: new Date() }
const result = await db.users.create({ data: newUser })
await kv.set(['last_user_updated'], newUser.id)
return result
} else {
const result = await db.users.update({ where: { id: user.id }, data: user })
await kv.set(['last_user_updated'], user.id)
return result
}
}
export const handler: Handlers<User | null> = {
async POST(req, _ctx) {
if (req.headers.get('content-type')?.includes('json')) {
const result = await createOrUpdate(UserPayload.parse(await req.json()))
return new Response(JSON.stringify(result))
} else {
const form = await req.formData()
const id = form.get('id')?.toString()
const avatarFile = form.get('avatar') as (File | null)
// validate png/jpg/webp?
if (!avatarFile && !id) {
throw new Error('invalid avatar file')
}
const user = UserPayload.parse({
id: id,
name: form.get('name')?.toString(),
color: form.get('color')?.toString(),
avatarUrl: '',
})
if (!id) {
delete user.id
} else {
const curUser = await db.users.findFirst({ where: { id: id } })
user.avatarUrl = curUser.avatarUrl
}
if (avatarFile) {
await Deno.mkdir('./static/uploads', { recursive: true })
// TODO: id will be undefined here
const name = `${id}-${avatarFile.name.replaceAll('/', '')}`
const localAvatarFile = await Deno.open(`./static/uploads/${name}`, {
create: true,
write: true,
})
await avatarFile.stream().pipeTo(localAvatarFile.writable)
user.avatarUrl = `/uploads/${name}`
}
await createOrUpdate(user)
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 userData = UserModel.pick({ id: true }).parse(data)
const result = await db.users.delete({ where: userData })
await kv.set(['last_user_updated'], userData.id)
return new Response(JSON.stringify(result))
},
async GET(req, ctx) {
// TODO: json or query params
const accept = req.headers.get('accept')
if (accept === 'text/event-stream') {
const stream = kv.watch<readonly unknown[]>([['last_user_updated']])
.getReader()
const body = new ReadableStream({
async start(controller) {
console.log(
`Streaming user updates to ${JSON.stringify(ctx.remoteAddr)}...`,
)
while (true) {
try {
const entry = await stream.read()
if (entry.done) {
return
}
let v: string
if (typeof entry.value === 'string') {
v = z.object({ value: z.string() }).parse(entry).value
} else {
continue
}
const user = await db.users.findFirst({
where: { id: v },
})
const chunk = `data: ${JSON.stringify(user)}\n\n`
controller.enqueue(new TextEncoder().encode(chunk))
} catch (e) {
console.error(`Error refreshing user:`, e)
}
}
},
cancel() {
stream.cancel()
console.log(
`Closed user updates stream to ${JSON.stringify(ctx.remoteAddr)}`,
)
},
})
return new Response(body, {
headers: {
'content-type': 'text/event-stream',
},
})
}
const data = await req.json().catch(() => {})
const userData = UserModel.pick({ id: true }).safeParse(data)
if (userData.success) {
return new Response(
JSON.stringify(await db.users.findFirst({ where: userData.data })),
)
} else {
return new Response(JSON.stringify(await db.users.findMany({})))
}
},
}