|
| 1 | +// @flow |
| 2 | +import UserError from '../../utils/UserError'; |
| 3 | +import { |
| 4 | + isAuthedResolver as requireAuth, |
| 5 | + canModerateCommunity, |
| 6 | +} from '../../utils/permissions'; |
| 7 | +import { events } from 'shared/analytics'; |
| 8 | +import { trackQueue } from 'shared/bull/queues'; |
| 9 | +import { publishThread, getWatercoolerThread } from '../../models/thread'; |
| 10 | +import { getChannelBySlug } from '../../models/channel'; |
| 11 | +import { setCommunityWatercoolerId } from '../../models/community'; |
| 12 | +import type { DBCommunity } from 'shared/types'; |
| 13 | +import type { GraphQLContext } from '../../'; |
| 14 | + |
| 15 | +type Args = { |
| 16 | + input: { |
| 17 | + id: string, |
| 18 | + }, |
| 19 | +}; |
| 20 | + |
| 21 | +export default requireAuth(async (_: any, args: Args, ctx: GraphQLContext) => { |
| 22 | + const { id: communityId } = args.input; |
| 23 | + const { user, loaders } = ctx; |
| 24 | + |
| 25 | + if (!(await canModerateCommunity(user.id, communityId, loaders))) { |
| 26 | + trackQueue.add({ |
| 27 | + userId: user.id, |
| 28 | + event: events.COMMUNITY_WATERCOOLER_ENABLED_FAILED, |
| 29 | + context: { communityId }, |
| 30 | + properties: { |
| 31 | + reason: 'no permission', |
| 32 | + }, |
| 33 | + }); |
| 34 | + |
| 35 | + return new UserError("You don't have permission to do this."); |
| 36 | + } |
| 37 | + |
| 38 | + const community: DBCommunity = await loaders.community.load(communityId); |
| 39 | + |
| 40 | + if (community.watercoolerId) return community; |
| 41 | + |
| 42 | + const channel = await getChannelBySlug('general', community.slug); |
| 43 | + |
| 44 | + if (!channel) { |
| 45 | + throw new Error( |
| 46 | + `Community ${community.slug} does not have general channel.` |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + const existingWatercooler = await getWatercoolerThread(community.id); |
| 51 | + |
| 52 | + if (existingWatercooler) |
| 53 | + return setCommunityWatercoolerId(community.id, existingWatercooler.id); |
| 54 | + |
| 55 | + const watercooler = await publishThread( |
| 56 | + { |
| 57 | + channelId: channel.id, |
| 58 | + communityId: community.id, |
| 59 | + content: { |
| 60 | + title: `${community.name} watercooler`, |
| 61 | + }, |
| 62 | + type: 'DRAFTJS', |
| 63 | + watercooler: true, |
| 64 | + }, |
| 65 | + user.id |
| 66 | + ); |
| 67 | + |
| 68 | + return setCommunityWatercoolerId(community.id, watercooler.id); |
| 69 | +}); |
0 commit comments