The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor Slack integration slash command handling
Kiran K5208c2f10cda
diff --git a/apps/web/app/api/slack/slash-commands/route.ts b/apps/web/app/api/slack/slash-commands/route.tsindex 7087e6a1cb..d79e51723c 100644--- a/apps/web/app/api/slack/slash-commands/route.ts+++ b/apps/web/app/api/slack/slash-commands/route.ts@@ -1,8 +1,8 @@-import { handleCreateShortLink } from "@/lib/integration/slack/slash-commands";+import { handleSlashCommand } from "@/lib/integration/slack/slash-commands";// Slack will send an HTTP POST request information to this URL when a user run the command /shorten <url> <key>export const POST = async (req: Request) => {- const { text } = await handleCreateShortLink(req);+ const { text } = await handleSlashCommand(req);return new Response(text);};diff --git a/apps/web/lib/integration/slack/callback.ts b/apps/web/lib/integration/slack/callback.tsindex cb0ff5c3b5..b4cd991443 100644--- a/apps/web/lib/integration/slack/callback.ts+++ b/apps/web/lib/integration/slack/callback.ts@@ -1 +1,84 @@-export {};+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { getSession } from "@/lib/auth";+import { installIntegration } from "@/lib/integration/install";+import { SlackCredential } from "@/lib/integration/slack/type";+import { prisma } from "@/lib/prisma";+import { redis } from "@/lib/upstash";+import z from "@/lib/zod";+import { getSearchParams } from "@dub/utils";+import { Project } from "@prisma/client";+import { redirect } from "next/navigation";++const schema = z.object({+ code: z.string(),+ state: z.string(),+});++export const installSlackIntegration = async (req: Request) => {+ let workspace: Pick<Project, "slug"> | null = null;++ try {+ const session = await getSession();++ if (!session?.user.id) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized",+ });+ }++ const { code, state } = schema.parse(getSearchParams(req.url));++ // Find workspace that initiated the Stripe app install+ const workspaceId = await redis.get<string>(`slack:install:state:${state}`);++ if (!workspaceId) {+ throw new DubApiError({+ code: "bad_request",+ message: "Unknown state",+ });+ }++ workspace = await prisma.project.findFirstOrThrow({+ where: {+ id: workspaceId,+ },+ select: {+ slug: true,+ },+ });++ const formData = new FormData();+ formData.append("code", code);+ formData.append("client_id", `${process.env.SLACK_CLIENT_ID}`);+ formData.append("client_secret", `${process.env.SLACK_CLIENT_SECRET}`);++ const response = await fetch("https://slack.com/api/oauth.v2.access", {+ method: "POST",+ body: formData,+ });++ const data = await response.json();++ const credentials: SlackCredential = {+ appId: data.app_id,+ botUserId: data.bot_user_id,+ scope: data.scope,+ accessToken: data.access_token,+ tokenType: data.token_type,+ authUser: data.authed_user,+ team: data.team,+ };++ await installIntegration({+ integrationSlug: "slack",+ userId: session.user.id,+ workspaceId,+ credentials,+ });+ } catch (e: any) {+ return handleAndReturnErrorResponse(e);+ }++ redirect(`${workspace.slug}/integrations/slack`);+};diff --git a/apps/web/lib/integration/slack/slash-commands.ts b/apps/web/lib/integration/slack/slash-commands.tsindex e6b2d8d330..ec4b5d34c9 100644--- a/apps/web/lib/integration/slack/slash-commands.ts+++ b/apps/web/lib/integration/slack/slash-commands.ts@@ -3,15 +3,19 @@ import { prisma } from "@/lib/prisma";import { WorkspaceProps } from "@/lib/types";import z from "@/lib/zod";import { createLinkBodySchema } from "@/lib/zod/schemas/links";+import { InstalledIntegration } from "@prisma/client";const schema = z.object({api_app_id: z.string(),team_id: z.string(),text: z.string().transform((text) => text.trim().split(" ")),+ command: z.enum(["/shorten"]),});-// Handle `/shorten` command from Slack-export const handleCreateShortLink = async (req: Request) => {+// Handle slash command from Slack+export const handleSlashCommand = async (+ req: Request,+): Promise<{ text: string }> => {const formData = await req.formData();const rawFormData = Object.fromEntries(formData.entries());const parsedInput = schema.safeParse(rawFormData);@@ -58,10 +62,7 @@ export const handleCreateShortLink = async (req: Request) => {};}- const [url, key] = data.text;- const body = createLinkBodySchema.parse({ url, key });-- const workspace = await prisma.project.findUniqueOrThrow({+ const workspace = (await prisma.project.findUniqueOrThrow({where: {id: installation.projectId,},@@ -69,7 +70,29 @@ export const handleCreateShortLink = async (req: Request) => {id: true,plan: true,},- });+ })) as WorkspaceProps;++ if (data.command === "/shorten") {+ return createShortLink({ data, workspace, installation });+ }++ return {+ text: "Invalid command.",+ };+};++// Handle `/shorten` command from Slack+const createShortLink = async ({+ data,+ workspace,+ installation,+}: {+ data: z.infer<typeof schema>;+ workspace: Pick<WorkspaceProps, "id" | "plan">;+ installation: InstalledIntegration;+}) => {+ const [url, key] = data.text;+ const body = createLinkBodySchema.parse({ url, key });const { link, error } = await processLink({payload: body,