forked from BRETT/BRETT
48 lines
1.6 KiB
TypeScript
48 lines
1.6 KiB
TypeScript
import { asc, desc, eq, inArray } from 'drizzle-orm'
|
|
import { commentAttachments, comments, uploads, users } from '../../db/schema'
|
|
import type { CommentAttachment } from '~~/shared/utils/attachments'
|
|
|
|
export default defineEventHandler(async () => {
|
|
const db = useDb()
|
|
const rows = await db
|
|
.select({
|
|
id: comments.id,
|
|
content: comments.content,
|
|
createdAt: comments.createdAt,
|
|
userName: users.name,
|
|
userId: users.id,
|
|
userColor: users.color,
|
|
userAvatar: users.avatar,
|
|
uploadId: uploads.id,
|
|
})
|
|
.from(comments)
|
|
.innerJoin(users, eq(comments.userId, users.id))
|
|
.innerJoin(uploads, eq(comments.uploadId, uploads.id))
|
|
.orderBy(desc(comments.createdAt))
|
|
.limit(15)
|
|
|
|
const commentIds = rows.map(r => r.id)
|
|
const attachmentRows = commentIds.length
|
|
? await db
|
|
.select()
|
|
.from(commentAttachments)
|
|
.where(inArray(commentAttachments.commentId, commentIds))
|
|
.orderBy(asc(commentAttachments.id))
|
|
: []
|
|
const attachmentsByComment = new Map<number, CommentAttachment[]>()
|
|
for (const a of attachmentRows) {
|
|
let list = attachmentsByComment.get(a.commentId)
|
|
if (!list) {
|
|
list = []
|
|
attachmentsByComment.set(a.commentId, list)
|
|
}
|
|
list.push({ id: a.id, name: a.originalName, url: `/uploads/attachments/${a.fileName}`, mimeType: a.mimeType, size: a.size, cover: a.cover, meta: a.meta as CommentAttachment['meta'] })
|
|
}
|
|
|
|
return rows.map(r => ({
|
|
...r,
|
|
userAvatarUrl: avatarUrl(r.userAvatar),
|
|
attachments: attachmentsByComment.get(r.id) ?? [],
|
|
}))
|
|
})
|