|
| 1 | +import { and, eq } from 'drizzle-orm'; |
| 2 | +import { database, PostRevisions, Posts, Profiles, SpaceFollows, SpaceMembers, Spaces } from '$lib/server/database'; |
| 3 | +import { createNotification, useFirstRow } from '$lib/server/utils'; |
| 4 | +import type { NotificationMaker } from './type'; |
| 5 | + |
| 6 | +export const SpaceNewPostNotificationMaker: NotificationMaker = async (postId: string) => { |
| 7 | + const post = await database |
| 8 | + .select({ |
| 9 | + permalink: Posts.permalink, |
| 10 | + title: PostRevisions.title, |
| 11 | + userId: Posts.userId, |
| 12 | + memberProfileId: SpaceMembers.profileId, |
| 13 | + memberProfileName: Profiles.name, |
| 14 | + spaceId: Spaces.id, |
| 15 | + spaceSlug: Spaces.slug, |
| 16 | + spaceName: Spaces.name, |
| 17 | + }) |
| 18 | + .from(Posts) |
| 19 | + .innerJoin(Spaces, eq(Posts.spaceId, Spaces.id)) |
| 20 | + .innerJoin(PostRevisions, eq(Posts.publishedRevisionId, PostRevisions.id)) |
| 21 | + .innerJoin( |
| 22 | + SpaceMembers, |
| 23 | + and( |
| 24 | + eq(SpaceMembers.spaceId, Posts.spaceId), |
| 25 | + eq(SpaceMembers.userId, Posts.userId), |
| 26 | + eq(SpaceMembers.state, 'ACTIVE'), |
| 27 | + ), |
| 28 | + ) |
| 29 | + .innerJoin(Profiles, eq(SpaceMembers.profileId, Profiles.id)) |
| 30 | + .where(and(eq(Posts.id, postId), eq(Posts.state, 'PUBLISHED'), eq(Posts.visibility, 'PUBLIC'))) |
| 31 | + .then(useFirstRow); |
| 32 | + |
| 33 | + if (!post) { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + const followerIds = await database |
| 38 | + .select({ |
| 39 | + userId: SpaceFollows.userId, |
| 40 | + }) |
| 41 | + .from(SpaceFollows) |
| 42 | + .where(and(eq(SpaceFollows.spaceId, post.spaceId))) |
| 43 | + .then((rows) => rows.map((row) => row.userId)); |
| 44 | + |
| 45 | + await Promise.all( |
| 46 | + followerIds.map(async (userId) => { |
| 47 | + await createNotification({ |
| 48 | + userId, |
| 49 | + category: 'NEW_POST', |
| 50 | + actorId: post.memberProfileId, |
| 51 | + data: { |
| 52 | + postId, |
| 53 | + }, |
| 54 | + pushTitle: post.spaceName, |
| 55 | + pushBody: `${post.title} 글이 올라왔어요.`, |
| 56 | + pushPath: `/${post.spaceSlug}/${post.permalink}`, |
| 57 | + }); |
| 58 | + }), |
| 59 | + ); |
| 60 | +}; |
0 commit comments