forked from BRETT/BRETT
53 lines
2.3 KiB
TypeScript
53 lines
2.3 KiB
TypeScript
import { and, count, desc, eq, max } from 'drizzle-orm'
|
|
import { comments, notifications, uploads, users } from '../../db/schema'
|
|
import { mentionedUserIds } from '../../../shared/utils/mentions'
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const user = await getSessionUser(event)
|
|
if (!user) {
|
|
return { notifications: [], unreadCount: 0 }
|
|
}
|
|
const db = useDb()
|
|
const threads = db.select({ id: max(notifications.id).as('thread_notification_id') }).from(notifications)
|
|
.where(and(eq(notifications.userId, user.id), eq(notifications.isRead, false)))
|
|
.groupBy(notifications.uploadId).as('thread_notifications')
|
|
const [total] = await db.select({ count: count() }).from(threads)
|
|
const rows = await db
|
|
.select({
|
|
id: notifications.id,
|
|
uploadId: notifications.uploadId,
|
|
commentId: notifications.commentId,
|
|
isRead: notifications.isRead,
|
|
createdAt: notifications.createdAt,
|
|
actorName: users.name,
|
|
actorColor: users.color,
|
|
content: comments.content,
|
|
uploadType: uploads.type,
|
|
fileName: uploads.fileName,
|
|
externalUrl: uploads.externalUrl,
|
|
previewImage: uploads.previewImage,
|
|
})
|
|
.from(notifications)
|
|
.innerJoin(threads, eq(notifications.id, threads.id))
|
|
.innerJoin(users, eq(notifications.actorId, users.id))
|
|
.innerJoin(comments, eq(notifications.commentId, comments.id))
|
|
.innerJoin(uploads, eq(notifications.uploadId, uploads.id))
|
|
.where(and(eq(notifications.userId, user.id), eq(notifications.isRead, false)))
|
|
.orderBy(desc(notifications.createdAt), desc(notifications.id))
|
|
.limit(30)
|
|
const mentionUsers = rows.some(row => row.content.includes('@'))
|
|
? await db.select({ id: users.id, name: users.name, color: users.color }).from(users)
|
|
: []
|
|
return {
|
|
notifications: rows.map((row) => {
|
|
const url = row.externalUrl ?? `/uploads/${row.fileName}`
|
|
const embedId = row.uploadType === 'youtube' && row.externalUrl ? getYoutubeId(row.externalUrl) : null
|
|
const thumbUrl = row.uploadType === 'youtube' && embedId
|
|
? youtubeThumbUrl(embedId)
|
|
: row.uploadType === 'image' ? url : row.uploadType === 'link' ? row.previewImage : null
|
|
return { ...row, url, thumbUrl, isMention: mentionedUserIds(row.content, mentionUsers).has(user.id) }
|
|
}),
|
|
unreadCount: Number(total?.count ?? 0),
|
|
}
|
|
})
|