homeman-deno/routes/api/user.ts

93 lines
2.8 KiB
TypeScript
Raw Normal View History

2024-01-07 10:55:18 -06:00
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'
2024-01-07 11:27:50 -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-09 21:52:47 -06:00
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 })
}
}
2024-01-07 10:55:18 -06:00
export const handler: Handlers<User | null> = {
async POST(req, _ctx) {
2024-01-07 11:27:50 -06:00
if (req.headers.get('content-type')?.includes('json')) {
2024-01-09 21:52:47 -06:00
const result = await createOrUpdate(UserPayload.parse(await req.json()))
return new Response(JSON.stringify(result))
2024-01-07 11:27:50 -06:00
} else {
const form = await req.formData()
2024-01-09 21:52:47 -06:00
const id = form.get('id')?.toString()
2024-01-07 11:27:50 -06:00
2024-01-09 21:52:47 -06:00
const avatarFile = form.get('avatar') as (File | null)
2024-01-07 11:27:50 -06:00
// validate png/jpg/webp?
2024-01-09 21:52:47 -06:00
if (!avatarFile && !id) {
throw new Error('invalid avatar file')
}
2024-01-07 11:27:50 -06:00
2024-01-09 21:52:47 -06:00
const user = UserPayload.parse({
id: id,
2024-01-07 11:27:50 -06:00
name: form.get('name')?.toString(),
color: form.get('color')?.toString(),
2024-01-09 21:52:47 -06:00
avatarUrl: '',
2024-01-07 11:27:50 -06:00
})
2024-01-09 21:52:47 -06:00
if (!id) {
delete user.id
2024-01-07 16:21:14 -06:00
} else {
2024-01-09 21:52:47 -06:00
const curUser = await db.users.findFirst({ where: { id: id } })
user.avatarUrl = curUser.avatarUrl
}
if (avatarFile) {
2024-01-07 16:21:14 -06:00
await Deno.mkdir('./static/uploads', { recursive: true })
2024-01-09 23:06:44 -06:00
// TODO: id will be undefined here
2024-01-09 21:52:47 -06:00
const name = `${id}-${avatarFile.name.replaceAll('/', '')}`
2024-01-07 16:21:14 -06:00
const localAvatarFile = await Deno.open(`./static/uploads/${name}`, {
create: true,
write: true,
})
await avatarFile.stream().pipeTo(localAvatarFile.writable)
2024-01-09 21:52:47 -06:00
user.avatarUrl = `/uploads/${name}`
2024-01-07 16:21:14 -06:00
}
2024-01-09 21:52:47 -06:00
await createOrUpdate(user)
2024-01-07 16:21:14 -06:00
const url = new URL(req.url)
url.pathname = '/admin'
return Response.redirect(url, 303)
}
2024-01-07 10:55:18 -06:00
},
async DELETE(req, _ctx) {
2024-01-07 11:27:50 -06:00
// TODO: form or query params or json
2024-01-07 11:38:25 -06:00
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)
2024-01-07 10:55:18 -06:00
const result = await db.users.delete({ where: userData })
return new Response(JSON.stringify(result))
},
async GET(req, _ctx) {
2024-01-07 11:27:50 -06:00
// TODO: json or query params
2024-01-07 10:55:18 -06:00
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({})))
}
},
}