Skip to content

Commit

Permalink
feat(api): ✨ Add routes for subscribing webhook
Browse files Browse the repository at this point in the history
  • Loading branch information
baptisteArno committed Feb 21, 2022
1 parent 5a80774 commit 68ae69f
Show file tree
Hide file tree
Showing 21 changed files with 470 additions and 175 deletions.
2 changes: 0 additions & 2 deletions apps/builder/.env.local.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
NEXT_PUBLIC_AUTH_MOCKING=disabled

DATABASE_URL=postgresql://postgres:@localhost:5432/typebot

ENCRYPTION_SECRET=q3t6v9y$B&E)H@McQfTjWnZr4u7x!z%C #256-bits secret (can be generated here: https://www.allkeysgenerator.com/Random/Security-Encryption-Key-Generator.aspx)
Expand Down
31 changes: 18 additions & 13 deletions apps/builder/components/dashboard/FolderContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@ import {
Wrap,
} from '@chakra-ui/react'
import { useTypebotDnd } from 'contexts/TypebotDndContext'
import { Typebot } from 'models'
import React, { useEffect, useState } from 'react'
import { createFolder, useFolders } from 'services/folders'
import { patchTypebot, useTypebots } from 'services/typebots'
import {
patchTypebot,
TypebotInDashboard,
useTypebots,
} from 'services/typebots'
import { AnnoucementModal } from './annoucements/AnnoucementModal'
import { BackButton } from './FolderContent/BackButton'
import { CreateBotButton } from './FolderContent/CreateBotButton'
Expand All @@ -42,7 +45,8 @@ export const FolderContent = ({ folder }: Props) => {
x: 0,
y: 0,
})
const [typebotDragCandidate, setTypebotDragCandidate] = useState<Typebot>()
const [typebotDragCandidate, setTypebotDragCandidate] =
useState<TypebotInDashboard>()
const { isOpen, onOpen, onClose } = useDisclosure()

const toast = useToast({
Expand Down Expand Up @@ -130,16 +134,17 @@ export const FolderContent = ({ folder }: Props) => {
}
useEventListener('mouseup', handleMouseUp)

const handleMouseDown = (typebot: Typebot) => (e: React.MouseEvent) => {
const element = e.currentTarget as HTMLDivElement
const rect = element.getBoundingClientRect()
setDraggablePosition({ x: rect.left, y: rect.top })
const x = e.clientX - rect.left
const y = e.clientY - rect.top
setRelativeDraggablePosition({ x, y })
setMouseDownPosition({ x: e.screenX, y: e.screenY })
setTypebotDragCandidate(typebot)
}
const handleMouseDown =
(typebot: TypebotInDashboard) => (e: React.MouseEvent) => {
const element = e.currentTarget as HTMLDivElement
const rect = element.getBoundingClientRect()
setDraggablePosition({ x: rect.left, y: rect.top })
const x = e.clientX - rect.left
const y = e.clientY - rect.top
setRelativeDraggablePosition({ x, y })
setMouseDownPosition({ x: e.screenX, y: e.screenY })
setTypebotDragCandidate(typebot)
}

const handleMouseMove = (e: MouseEvent) => {
if (!typebotDragCandidate) return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { useTypebotDnd } from 'contexts/TypebotDndContext'
import { useDebounce } from 'use-debounce'

type ChatbotCardProps = {
typebot: Typebot
typebot: Pick<Typebot, 'id' | 'publishedTypebotId' | 'name'>
onTypebotDeleted: () => void
onMouseDown: (e: React.MouseEvent<HTMLButtonElement>) => void
}
Expand Down Expand Up @@ -66,7 +66,7 @@ export const TypebotButton = ({

const handleDuplicateClick = async (e: React.MouseEvent) => {
e.stopPropagation()
const { data: createdTypebot, error } = await duplicateTypebot(typebot)
const { data: createdTypebot, error } = await duplicateTypebot(typebot.id)
if (error)
return toast({
title: "Couldn't duplicate typebot",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Box, BoxProps, Flex, Text, VStack } from '@chakra-ui/react'
import { GlobeIcon, ToolIcon } from 'assets/icons'
import { Typebot } from 'models'
import { TypebotInDashboard } from 'services/typebots'

type Props = {
typebot: Typebot
typebot: TypebotInDashboard
} & BoxProps

export const TypebotCardOverlay = ({ typebot, ...props }: Props) => {
Expand Down
8 changes: 4 additions & 4 deletions apps/builder/contexts/TypebotDndContext.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Typebot } from 'models'
import {
createContext,
Dispatch,
Expand All @@ -8,18 +7,19 @@ import {
useEffect,
useState,
} from 'react'
import { TypebotInDashboard } from 'services/typebots'

const typebotDndContext = createContext<{
draggedTypebot?: Typebot
setDraggedTypebot: Dispatch<SetStateAction<Typebot | undefined>>
draggedTypebot?: TypebotInDashboard
setDraggedTypebot: Dispatch<SetStateAction<TypebotInDashboard | undefined>>
mouseOverFolderId?: string | null
setMouseOverFolderId: Dispatch<SetStateAction<string | undefined | null>>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
}>({})

export const TypebotDndContext = ({ children }: { children: ReactNode }) => {
const [draggedTypebot, setDraggedTypebot] = useState<Typebot>()
const [draggedTypebot, setDraggedTypebot] = useState<TypebotInDashboard>()
const [mouseOverFolderId, setMouseOverFolderId] = useState<string | null>()

useEffect(() => {
Expand Down
3 changes: 2 additions & 1 deletion apps/builder/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { NextApiRequest, NextApiResponse } from 'next'
import { isNotDefined } from 'utils'
import { User } from 'db'
import { randomUUID } from 'crypto'
import { withSentry } from '@sentry/nextjs'

const providers: Provider[] = [
EmailProvider({
Expand Down Expand Up @@ -77,4 +78,4 @@ const generateApiToken = async (userId: string) => {
return apiToken
}

export default handler
export default withSentry(handler)
3 changes: 2 additions & 1 deletion apps/builder/pages/api/integrations/email/test-config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { withSentry } from '@sentry/nextjs'
import { SmtpCredentialsData } from 'models'
import { NextApiRequest, NextApiResponse } from 'next'
import { createTransport } from 'nodemailer'
Expand Down Expand Up @@ -25,4 +26,4 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
}
}

export default handler
export default withSentry(handler)
1 change: 1 addition & 0 deletions apps/builder/pages/api/typebots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
ownerId: user.id,
folderId,
},
select: { name: true, publishedTypebotId: true, id: true },
})
return res.send({ typebots })
}
Expand Down
27 changes: 19 additions & 8 deletions apps/builder/services/typebots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ import { stringify } from 'qs'
import { isChoiceInput, isConditionStep, sendRequest } from 'utils'
import { parseBlocksToPublicBlocks } from './publicTypebot'

export type TypebotInDashboard = Pick<
Typebot,
'id' | 'name' | 'publishedTypebotId'
>
export const useTypebots = ({
folderId,
onError,
Expand All @@ -59,11 +63,10 @@ export const useTypebots = ({
onError: (error: Error) => void
}) => {
const params = stringify({ folderId })
const { data, error, mutate } = useSWR<{ typebots: Typebot[] }, Error>(
`/api/typebots?${params}`,
fetcher,
{ dedupingInterval: 0 }
)
const { data, error, mutate } = useSWR<
{ typebots: TypebotInDashboard[] },
Error
>(`/api/typebots?${params}`, fetcher, { dedupingInterval: 0 })
if (error) onError(error)
return {
typebots: data?.typebots,
Expand Down Expand Up @@ -93,11 +96,13 @@ export const importTypebot = async (typebot: Typebot) =>
body: typebot,
})

export const duplicateTypebot = async (typebot: Typebot) => {
export const duplicateTypebot = async (typebotId: string) => {
const { data: typebotToDuplicate } = await getTypebot(typebotId)
if (!typebotToDuplicate) return { error: new Error('Typebot not found') }
const duplicatedTypebot: Omit<Typebot, 'id'> = omit(
{
...typebot,
name: `${typebot.name} copy`,
...typebotToDuplicate,
name: `${typebotToDuplicate.name} copy`,
publishedTypebotId: null,
publicId: null,
},
Expand All @@ -110,6 +115,12 @@ export const duplicateTypebot = async (typebot: Typebot) => {
})
}

const getTypebot = (typebotId: string) =>
sendRequest<Typebot>({
url: `/api/typebots/${typebotId}`,
method: 'GET',
})

export const deleteTypebot = async (id: string) =>
sendRequest({
url: `/api/typebots/${id}`,
Expand Down
20 changes: 20 additions & 0 deletions apps/viewer/pages/api/typebots.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { withSentry } from '@sentry/nextjs'
import prisma from 'libs/prisma'
import { NextApiRequest, NextApiResponse } from 'next'
import { authenticateUser } from 'services/api/utils'
import { methodNotAllowed } from 'utils'

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'GET') {
const user = await authenticateUser(req)
if (!user) return res.status(401).json({ message: 'Not authenticated' })
const typebots = await prisma.typebot.findMany({
where: { ownerId: user.id },
select: { name: true, publishedTypebotId: true, id: true },
})
return res.send({ typebots })
}
return methodNotAllowed(res)
}

export default withSentry(handler)
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { withSentry } from '@sentry/nextjs'
import { Prisma } from 'db'
import prisma from 'libs/prisma'
import { IntegrationStepType, Typebot } from 'models'
import { NextApiRequest, NextApiResponse } from 'next'
import { authenticateUser } from 'services/api/utils'
import { methodNotAllowed } from 'utils'

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'PATCH') {
const user = await authenticateUser(req)
if (!user) return res.status(401).json({ message: 'Not authenticated' })
const body = req.body as Record<string, string>
if (!('url' in body))
return res.status(403).send({ message: 'url is missing in body' })
const { url } = body
const typebotId = req.query.typebotId.toString()
const stepId = req.query.stepId.toString()
const typebot = (await prisma.typebot.findUnique({
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
})) as Typebot | undefined
if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
try {
const updatedTypebot = addUrlToWebhookStep(url, typebot, stepId)
await prisma.typebot.update({
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
data: { blocks: updatedTypebot.blocks as Prisma.JsonArray },
})
return res.send({ message: 'success' })
} catch (err) {
return res
.status(400)
.send({ message: "stepId doesn't point to a Webhook step" })
}
}
return methodNotAllowed(res)
}

const addUrlToWebhookStep = (
url: string,
typebot: Typebot,
stepId: string
): Typebot => ({
...typebot,
blocks: typebot.blocks.map((b) => ({
...b,
steps: b.steps.map((s) => {
if (s.id === stepId) {
if (s.type !== IntegrationStepType.WEBHOOK) throw new Error()
return { ...s, webhook: { ...s.webhook, url } }
}
return s
}),
})),
})

export default withSentry(handler)
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { withSentry } from '@sentry/nextjs'
import { Prisma } from 'db'
import prisma from 'libs/prisma'
import { IntegrationStepType, Typebot } from 'models'
import { NextApiRequest, NextApiResponse } from 'next'
import { authenticateUser } from 'services/api/utils'
import { omit } from 'services/utils'
import { methodNotAllowed } from 'utils'

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'DELETE') {
const user = await authenticateUser(req)
if (!user) return res.status(401).json({ message: 'Not authenticated' })
const typebotId = req.query.typebotId.toString()
const stepId = req.query.stepId.toString()
const typebot = (await prisma.typebot.findUnique({
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
})) as Typebot | undefined
if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
try {
const updatedTypebot = removeUrlFromWebhookStep(typebot, stepId)
await prisma.typebot.update({
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
data: {
blocks: updatedTypebot.blocks as Prisma.JsonArray,
},
})
return res.send({ message: 'success' })
} catch (err) {
return res
.status(400)
.send({ message: "stepId doesn't point to a Webhook step" })
}
}
return methodNotAllowed(res)
}

const removeUrlFromWebhookStep = (
typebot: Typebot,
stepId: string
): Typebot => ({
...typebot,
blocks: typebot.blocks.map((b) => ({
...b,
steps: b.steps.map((s) => {
if (s.id === stepId) {
if (s.type !== IntegrationStepType.WEBHOOK) throw new Error()
return { ...s, webhook: omit(s.webhook, 'url') }
}
return s
}),
})),
})

export default withSentry(handler)
37 changes: 37 additions & 0 deletions apps/viewer/pages/api/typebots/[typebotId]/webhookSteps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { withSentry } from '@sentry/nextjs'
import prisma from 'libs/prisma'
import { Block, IntegrationStepType } from 'models'
import { NextApiRequest, NextApiResponse } from 'next'
import { authenticateUser } from 'services/api/utils'
import { methodNotAllowed } from 'utils'

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'GET') {
const user = await authenticateUser(req)
if (!user) return res.status(401).json({ message: 'Not authenticated' })
const typebotId = req.query.typebotId.toString()
const typebot = await prisma.typebot.findUnique({
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
select: { blocks: true },
})
const emptyWebhookSteps = (typebot?.blocks as Block[]).reduce<
{ blockId: string; stepId: string; name: string }[]
>((emptyWebhookSteps, block) => {
const steps = block.steps.filter(
(step) => step.type === IntegrationStepType.WEBHOOK && !step.webhook.url
)
return [
...emptyWebhookSteps,
...steps.map((s) => ({
blockId: s.blockId,
stepId: s.id,
name: `${block.title} > ${s.id}`,
})),
]
}, [])
return res.send({ steps: emptyWebhookSteps })
}
return methodNotAllowed(res)
}

export default withSentry(handler)
16 changes: 16 additions & 0 deletions apps/viewer/pages/api/users/me.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { withSentry } from '@sentry/nextjs'
import { NextApiRequest, NextApiResponse } from 'next'
import { authenticateUser } from 'services/api/utils'
import { isNotDefined, methodNotAllowed } from 'utils'

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'GET') {
const user = await authenticateUser(req)
if (isNotDefined(user))
return res.status(404).send({ message: 'User not found' })
return res.send({ id: user.id })
}
return methodNotAllowed(res)
}

export default withSentry(handler)
Loading

2 comments on commit 68ae69f

@vercel
Copy link

@vercel vercel bot commented on 68ae69f Feb 21, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on 68ae69f Feb 21, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

builder-v2 – ./apps/builder

builder-v2-git-main-typebot-io.vercel.app
app.typebot.io
builder-v2-typebot-io.vercel.app

Please sign in to comment.