|
| 1 | +import { and, eq } from 'drizzle-orm'; |
| 2 | +import { database, PostComments, PostRevisions, Posts, Profiles, Spaces } from '$lib/server/database'; |
| 3 | +import { createNotification, useFirstRow } from '$lib/server/utils'; |
| 4 | +import type { NotificationMaker } from './type'; |
| 5 | + |
| 6 | +export const commentNotificationMaker: NotificationMaker = async (commentId) => { |
| 7 | + const comment = await database |
| 8 | + .select({ |
| 9 | + id: PostComments.id, |
| 10 | + content: PostComments.content, |
| 11 | + commenterId: PostComments.userId, |
| 12 | + profileId: PostComments.profileId, |
| 13 | + profileName: Profiles.name, |
| 14 | + spaceId: Posts.spaceId, |
| 15 | + spaceSlug: Spaces.slug, |
| 16 | + postPermalink: Posts.permalink, |
| 17 | + postWriterId: Posts.userId, |
| 18 | + postTitle: PostRevisions.title, |
| 19 | + parentId: PostComments.parentId, |
| 20 | + }) |
| 21 | + .from(PostComments) |
| 22 | + .innerJoin(Posts, eq(PostComments.postId, Posts.id)) |
| 23 | + .innerJoin(Spaces, eq(Posts.spaceId, Spaces.id)) |
| 24 | + .innerJoin(PostRevisions, eq(Posts.publishedRevisionId, PostRevisions.id)) |
| 25 | + .innerJoin(Profiles, eq(PostComments.profileId, Profiles.id)) |
| 26 | + .where(and(eq(PostComments.id, commentId), eq(PostComments.state, 'ACTIVE'))) |
| 27 | + .then(useFirstRow); |
| 28 | + |
| 29 | + if (!comment || !comment.spaceId) { |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + let notifiedUserId = comment.postWriterId; |
| 34 | + |
| 35 | + if (comment.parentId) { |
| 36 | + const parentComment = await database |
| 37 | + .select({ |
| 38 | + userId: PostComments.userId, |
| 39 | + }) |
| 40 | + .from(PostComments) |
| 41 | + .where(and(eq(PostComments.id, comment.parentId), eq(PostComments.state, 'ACTIVE'))) |
| 42 | + .then(useFirstRow); |
| 43 | + |
| 44 | + if (parentComment) { |
| 45 | + if (parentComment.userId === comment.commenterId) { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + notifiedUserId = parentComment.userId; |
| 50 | + } |
| 51 | + } else if (notifiedUserId === comment.commenterId) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + await createNotification({ |
| 56 | + userId: notifiedUserId, |
| 57 | + category: 'COMMENT', |
| 58 | + actorId: comment.profileId, |
| 59 | + data: { |
| 60 | + commentId: comment.id, |
| 61 | + }, |
| 62 | + pushTitle: comment.postTitle ?? '(제목 없음)', |
| 63 | + pushBody: `${comment.profileName}님이 "${comment.content}" 댓글을 남겼어요.`, |
| 64 | + pushPath: `/${comment.spaceSlug}/${comment.postPermalink}`, |
| 65 | + }); |
| 66 | +}; |
0 commit comments