|
| 1 | +import { db } from "@/database/db"; |
| 2 | +import { SlackInstallationTable } from "@/database/schema.sql"; |
| 3 | +import { eq } from "drizzle-orm"; |
| 4 | +import { InstallProvider, Installation } from "@slack/oauth"; |
| 5 | +import { Resource } from "sst"; |
| 6 | +import { WebClient } from "@slack/web-api"; |
| 7 | + |
| 8 | +export const client = new WebClient(); |
| 9 | + |
| 10 | +export const installer = new InstallProvider({ |
| 11 | + clientId: Resource.SlackClientId.value, |
| 12 | + clientSecret: Resource.SlackClientSecret.value, |
| 13 | + stateSecret: Resource.SlackSigningSecret.value, |
| 14 | + installationStore: { |
| 15 | + storeInstallation: async (installation) => { |
| 16 | + if (installation.isEnterpriseInstall) { |
| 17 | + throw new Error("Enterprise installations are not supported"); |
| 18 | + } |
| 19 | + await db |
| 20 | + .insert(SlackInstallationTable) |
| 21 | + .values({ |
| 22 | + teamId: installation.team!.id, |
| 23 | + teamName: installation.team!.name!, |
| 24 | + bot: { |
| 25 | + id: installation.bot!.id, |
| 26 | + token: installation.bot!.token, |
| 27 | + scopes: installation.bot!.scopes, |
| 28 | + userId: installation.bot!.userId, |
| 29 | + }, |
| 30 | + incomingWebhook: { |
| 31 | + channel: installation.incomingWebhook!.channel!, |
| 32 | + channelId: installation.incomingWebhook!.channelId!, |
| 33 | + configurationUrl: installation.incomingWebhook!.configurationUrl!, |
| 34 | + url: installation.incomingWebhook!.url!, |
| 35 | + }, |
| 36 | + }) |
| 37 | + .onConflictDoNothing(); |
| 38 | + }, |
| 39 | + fetchInstallation: async (installQuery) => { |
| 40 | + if (!installQuery.teamId) { |
| 41 | + throw new Error("Team ID is required"); |
| 42 | + } |
| 43 | + |
| 44 | + const [installation] = await db |
| 45 | + .select() |
| 46 | + .from(SlackInstallationTable) |
| 47 | + .where(eq(SlackInstallationTable.teamId, installQuery.teamId!)); |
| 48 | + |
| 49 | + if (!installation) { |
| 50 | + throw new Error("Installation not found"); |
| 51 | + } |
| 52 | + |
| 53 | + return { |
| 54 | + team: { |
| 55 | + id: installation.teamId, |
| 56 | + name: installation.teamName, |
| 57 | + }, |
| 58 | + bot: { |
| 59 | + id: installation.bot.id, |
| 60 | + token: installation.bot.token, |
| 61 | + scopes: installation.bot.scopes, |
| 62 | + userId: installation.bot.userId, |
| 63 | + }, |
| 64 | + incomingWebhook: installation.incomingWebhook, |
| 65 | + authVersion: "v2", |
| 66 | + isEnterpriseInstall: false, |
| 67 | + } as Installation<"v2", false>; |
| 68 | + }, |
| 69 | + deleteInstallation: async (installQuery) => { |
| 70 | + if (!installQuery.teamId) { |
| 71 | + throw new Error("Team ID is required"); |
| 72 | + } |
| 73 | + await db.delete(SlackInstallationTable).where(eq(SlackInstallationTable.teamId, installQuery.teamId!)); |
| 74 | + }, |
| 75 | + }, |
| 76 | +}); |
0 commit comments