File uploads

This commit is contained in:
Daniel Flanagan 2024-01-07 11:27:50 -06:00
parent 81a9c13e73
commit 1de725a54f
Signed by: lytedev
GPG key ID: 5B2020A0F9921EF4
3 changed files with 48 additions and 6 deletions

2
.gitignore vendored
View file

@ -15,3 +15,5 @@ node_modules/
*.db *.db
*.db-wal *.db-wal
*.db-shm *.db-shm
/static/uploads

View file

@ -30,7 +30,12 @@ export function Admin({ users, todos }: Props) {
</Button> </Button>
</header> </header>
<form class='p-4 gap-4 flex flex-col' action='/api/user' method='post'> <form
class='p-4 gap-4 flex flex-col'
action='/api/user'
method='post'
encType='multipart/form-data'
>
<Label for='name'> <Label for='name'>
Name Name
<Input autofocus name='name' /> <Input autofocus name='name' />
@ -87,7 +92,7 @@ export function Admin({ users, todos }: Props) {
</table> </table>
<header class='flex items-center border-b-2 border-stone-500/20 '> <header class='flex items-center border-b-2 border-stone-500/20 '>
<h1 class='p-5 text-2xl'> <h1 class='p-5 text-2xl'>
Todos ({users.length}) Todos ({todos.length})
</h1> </h1>
<Button>+</Button> <Button>+</Button>
</header> </header>

View file

@ -1,29 +1,64 @@
import { Handlers } from '$fresh/server.ts' import { Handlers } from '$fresh/server.ts'
import { db, User, UserModel } from '@homeman/models.ts' import { db, User, UserModel } from '@homeman/models.ts'
import { ulid } from 'https://deno.land/x/ulid@v0.3.0/mod.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 UserCreate = UserModel.omit({ id: true, createdAt: true }) const UserCreate = UserModel.omit({ id: true, createdAt: true })
type UserCreate = z.infer<typeof UserCreate>
export const handler: Handlers<User | null> = { export const handler: Handlers<User | null> = {
async POST(req, _ctx) { async POST(req, _ctx) {
const formData = await req.formData() // handle json or form posts
console.log('user form data POSTed', formData) let user: UserCreate
const user = UserCreate.parse(formData) const newId = ulid()
const newUser: User = { ...user, id: ulid(), createdAt: new Date() } if (req.headers.get('content-type')?.includes('json')) {
user = UserCreate.parse(req.json())
} else {
const form = await req.formData()
const avatarFile = form.get('avatar') as File
if (!avatarFile) {
throw new Error('invalid avatar file')
}
// validate png/jpg/webp?
await Deno.mkdir('./static/uploads', { recursive: true })
const name = `${newId}-${avatarFile.name.replaceAll('/', '')}`
const localAvatarFile = await Deno.open(`./static/uploads/${name}`, {
create: true,
write: true,
})
await avatarFile.stream().pipeTo(localAvatarFile.writable)
user = UserCreate.parse({
name: form.get('name')?.toString(),
avatarUrl: `/uploads/${name}`,
color: form.get('color')?.toString(),
})
}
// post processing
if (user.color && user.color[0] == '#') {
user.color = user.color.substring(1)
}
const newUser: User = { ...user, id: newId, createdAt: new Date() }
const result = await db.users.create({ data: newUser }) const result = await db.users.create({ data: newUser })
return new Response(JSON.stringify(result)) return new Response(JSON.stringify(result))
}, },
async PUT(req, _ctx) { async PUT(req, _ctx) {
// TODO: form or json
const user = UserModel.parse(await req.json()) const user = UserModel.parse(await req.json())
const result = await db.users.update({ data: user }) const result = await db.users.update({ data: user })
return new Response(JSON.stringify(result)) return new Response(JSON.stringify(result))
}, },
async DELETE(req, _ctx) { async DELETE(req, _ctx) {
// TODO: form or query params or json
const userData = UserModel.pick({ id: true }).parse(await req.json()) const userData = UserModel.pick({ id: true }).parse(await req.json())
const result = await db.users.delete({ where: userData }) const result = await db.users.delete({ where: userData })
return new Response(JSON.stringify(result)) return new Response(JSON.stringify(result))
}, },
async GET(req, _ctx) { async GET(req, _ctx) {
// TODO: json or query params
const data = await req.json().catch(() => {}) const data = await req.json().catch(() => {})
const userData = UserModel.pick({ id: true }).safeParse(data) const userData = UserModel.pick({ id: true }).safeParse(data)
if (userData.success) { if (userData.success) {