forked from BRETT/BRETT
52 lines
1.8 KiB
TypeScript
52 lines
1.8 KiB
TypeScript
import { and, desc, eq } from 'drizzle-orm'
|
|
import { favorites, threadSubscriptions, uploads, users } from '../../../db/schema'
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const user = await requireUser(event)
|
|
const id = getRouterParam(event, 'id') ?? ''
|
|
if (!/^[A-Za-z0-9]{1,16}$/.test(id)) {
|
|
throw createError({ statusCode: 400, statusMessage: 'Ungültige ID' })
|
|
}
|
|
const db = useDb()
|
|
|
|
const exists = await db
|
|
.select({ id: uploads.id })
|
|
.from(uploads)
|
|
.where(eq(uploads.id, id))
|
|
.limit(1)
|
|
if (!exists.length) {
|
|
throw createError({ statusCode: 404, statusMessage: 'Upload nicht gefunden' })
|
|
}
|
|
|
|
const existing = await db
|
|
.select()
|
|
.from(favorites)
|
|
.where(and(eq(favorites.uploadId, id), eq(favorites.userId, user.id)))
|
|
.limit(1)
|
|
|
|
if (existing.length) {
|
|
await db.delete(favorites).where(and(eq(favorites.uploadId, id), eq(favorites.userId, user.id)))
|
|
}
|
|
else {
|
|
await db.transaction(async (tx) => {
|
|
await tx.insert(favorites).values({ uploadId: id, userId: user.id })
|
|
await ensureThreadSubscription(id, user.id, tx)
|
|
})
|
|
}
|
|
|
|
const favRows = await db
|
|
.select({ id: users.id, name: users.name, color: users.color, avatar: users.avatar })
|
|
.from(favorites)
|
|
.innerJoin(users, eq(favorites.userId, users.id))
|
|
.where(eq(favorites.uploadId, id))
|
|
.orderBy(desc(favorites.createdAt))
|
|
|
|
const [subscription] = await db.select({ enabled: threadSubscriptions.enabled }).from(threadSubscriptions)
|
|
.where(and(eq(threadSubscriptions.uploadId, id), eq(threadSubscriptions.userId, user.id))).limit(1)
|
|
return {
|
|
isSubscribed: subscription?.enabled ?? false,
|
|
favorited: !existing.length,
|
|
favoritedBy: favRows.map(f => ({ id: f.id, name: f.name, color: f.color, avatarUrl: avatarUrl(f.avatar) })),
|
|
}
|
|
})
|