homeman-deno/routes/api/user.ts

93 lines
2.8 KiB
TypeScript

import { Handlers } from '$fresh/server.ts'
import { db, User, UserModel } 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 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() }
return await db.users.create({ data: newUser })
} else {
return await db.users.update({ where: { id: user.id }, data: user })
}
}
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 })
return new Response(JSON.stringify(result))
},
async GET(req, _ctx) {
// TODO: json or query params
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({})))
}
},
}