2024-01-07 10:55:18 -06:00
|
|
|
import { Handlers } from '$fresh/server.ts'
|
2024-01-17 15:10:28 -06:00
|
|
|
import { db, kv, User, UserModel } from '@homeman/models.ts'
|
2024-01-07 10:55:18 -06:00
|
|
|
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() }
|
2024-01-17 15:10:28 -06:00
|
|
|
const result = await db.users.create({ data: newUser })
|
|
|
|
await kv.set(['last_user_updated'], newUser.id)
|
|
|
|
return result
|
2024-01-09 21:52:47 -06:00
|
|
|
} else {
|
2024-01-17 15:10:28 -06:00
|
|
|
const result = await db.users.update({ where: { id: user.id }, data: user })
|
|
|
|
await kv.set(['last_user_updated'], user.id)
|
|
|
|
return result
|
2024-01-09 21:52:47 -06:00
|
|
|
}
|
|
|
|
}
|
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 })
|
2024-01-17 15:10:28 -06:00
|
|
|
await kv.set(['last_user_updated'], userData.id)
|
2024-01-07 10:55:18 -06:00
|
|
|
return new Response(JSON.stringify(result))
|
|
|
|
},
|
2024-01-17 15:10:28 -06:00
|
|
|
async GET(req, ctx) {
|
2024-01-07 11:27:50 -06:00
|
|
|
// TODO: json or query params
|
2024-01-17 15:10:28 -06:00
|
|
|
const accept = req.headers.get('accept')
|
|
|
|
if (accept === 'text/event-stream') {
|
|
|
|
const stream = kv.watch([['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
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof entry.value !== 'string') {
|
|
|
|
console.error('Invalid last_user_updated:', entry.value)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
const user = await db.users.findFirst({
|
|
|
|
where: { id: entry.value },
|
|
|
|
})
|
|
|
|
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',
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
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({})))
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|