feat(api): ✨ Add routes for subscribing webhook
This commit is contained in:
@ -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)
|
||||
|
@ -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'
|
||||
@ -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({
|
||||
@ -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
|
||||
|
@ -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
|
||||
}
|
||||
@ -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",
|
||||
|
@ -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) => {
|
||||
|
@ -1,4 +1,3 @@
|
||||
import { Typebot } from 'models'
|
||||
import {
|
||||
createContext,
|
||||
Dispatch,
|
||||
@ -8,10 +7,11 @@ 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
|
||||
@ -19,7 +19,7 @@ const typebotDndContext = createContext<{
|
||||
}>({})
|
||||
|
||||
export const TypebotDndContext = ({ children }: { children: ReactNode }) => {
|
||||
const [draggedTypebot, setDraggedTypebot] = useState<Typebot>()
|
||||
const [draggedTypebot, setDraggedTypebot] = useState<TypebotInDashboard>()
|
||||
const [mouseOverFolderId, setMouseOverFolderId] = useState<string | null>()
|
||||
|
||||
useEffect(() => {
|
||||
|
@ -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({
|
||||
@ -77,4 +78,4 @@ const generateApiToken = async (userId: string) => {
|
||||
return apiToken
|
||||
}
|
||||
|
||||
export default handler
|
||||
export default withSentry(handler)
|
||||
|
@ -1,3 +1,4 @@
|
||||
import { withSentry } from '@sentry/nextjs'
|
||||
import { SmtpCredentialsData } from 'models'
|
||||
import { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { createTransport } from 'nodemailer'
|
||||
@ -25,4 +26,4 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
}
|
||||
}
|
||||
|
||||
export default handler
|
||||
export default withSentry(handler)
|
||||
|
@ -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 })
|
||||
}
|
||||
|
@ -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,
|
||||
@ -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,
|
||||
@ -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,
|
||||
},
|
||||
@ -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}`,
|
||||
|
20
apps/viewer/pages/api/typebots.ts
Normal file
20
apps/viewer/pages/api/typebots.ts
Normal file
@ -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)
|
@ -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)
|
@ -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
apps/viewer/pages/api/typebots/[typebotId]/webhookSteps.ts
Normal file
37
apps/viewer/pages/api/typebots/[typebotId]/webhookSteps.ts
Normal file
@ -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
apps/viewer/pages/api/users/me.ts
Normal file
16
apps/viewer/pages/api/users/me.ts
Normal file
@ -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)
|
@ -1,6 +1,5 @@
|
||||
import {
|
||||
Block,
|
||||
CredentialsType,
|
||||
defaultSettings,
|
||||
defaultTheme,
|
||||
PublicBlock,
|
||||
@ -8,39 +7,31 @@ import {
|
||||
Step,
|
||||
Typebot,
|
||||
} from 'models'
|
||||
import { PrismaClient, User } from 'db'
|
||||
import { PrismaClient } from 'db'
|
||||
import { readFileSync } from 'fs'
|
||||
import { encrypt } from 'utils'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export const teardownDatabase = async () => {
|
||||
const ownerFilter = {
|
||||
where: { ownerId: { in: ['freeUser', 'proUser'] } },
|
||||
}
|
||||
await prisma.user.deleteMany({
|
||||
where: { id: { in: ['freeUser', 'proUser'] } },
|
||||
})
|
||||
await prisma.credentials.deleteMany(ownerFilter)
|
||||
return prisma.typebot.deleteMany(ownerFilter)
|
||||
export const teardownDatabase = () => {
|
||||
try {
|
||||
return prisma.user.delete({
|
||||
where: { id: 'user' },
|
||||
})
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export const setupDatabase = async () => {
|
||||
await createUsers()
|
||||
return createCredentials()
|
||||
}
|
||||
export const setupDatabase = () => createUser()
|
||||
|
||||
export const createUsers = () =>
|
||||
prisma.user.createMany({
|
||||
data: [
|
||||
{ id: 'freeUser', email: 'free-user@email.com', name: 'Free user' },
|
||||
{ id: 'proUser', email: 'pro-user@email.com', name: 'Pro user' },
|
||||
],
|
||||
export const createUser = () =>
|
||||
prisma.user.create({
|
||||
data: {
|
||||
id: 'user',
|
||||
email: 'user@email.com',
|
||||
name: 'User',
|
||||
apiToken: 'userToken',
|
||||
},
|
||||
})
|
||||
|
||||
export const getSignedInUser = (email: string) =>
|
||||
prisma.user.findFirst({ where: { email } })
|
||||
|
||||
export const createTypebots = async (partialTypebots: Partial<Typebot>[]) => {
|
||||
await prisma.typebot.createMany({
|
||||
data: partialTypebots.map(parseTestTypebot) as any[],
|
||||
@ -52,36 +43,6 @@ export const createTypebots = async (partialTypebots: Partial<Typebot>[]) => {
|
||||
})
|
||||
}
|
||||
|
||||
const createCredentials = () => {
|
||||
const { encryptedData, iv } = encrypt({
|
||||
expiry_date: 1642441058842,
|
||||
access_token:
|
||||
'ya29.A0ARrdaM--PV_87ebjywDJpXKb77NBFJl16meVUapYdfNv6W6ZzqqC47fNaPaRjbDbOIIcp6f49cMaX5ndK9TAFnKwlVqz3nrK9nLKqgyDIhYsIq47smcAIZkK56SWPx3X3DwAFqRu2UPojpd2upWwo-3uJrod',
|
||||
// This token is linked to a test Google account (typebot.test.user@gmail.com)
|
||||
refresh_token:
|
||||
'1//039xWRt8YaYa3CgYIARAAGAMSNwF-L9Iru9FyuTrDSa7lkSceggPho83kJt2J29G69iEhT1C6XV1vmo6bQS9puL_R2t8FIwR3gek',
|
||||
})
|
||||
return prisma.credentials.createMany({
|
||||
data: [
|
||||
{
|
||||
name: 'test2@gmail.com',
|
||||
ownerId: 'proUser',
|
||||
type: CredentialsType.GOOGLE_SHEETS,
|
||||
data: encryptedData,
|
||||
iv,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
export const updateUser = (data: Partial<User>) =>
|
||||
prisma.user.update({
|
||||
data,
|
||||
where: {
|
||||
id: 'proUser',
|
||||
},
|
||||
})
|
||||
|
||||
const parseTypebotToPublicTypebot = (
|
||||
id: string,
|
||||
typebot: Typebot
|
||||
@ -110,7 +71,7 @@ const parseTestTypebot = (partialTypebot: Partial<Typebot>): Typebot => ({
|
||||
id: partialTypebot.id ?? 'typebot',
|
||||
folderId: null,
|
||||
name: 'My typebot',
|
||||
ownerId: 'proUser',
|
||||
ownerId: 'user',
|
||||
theme: defaultTheme,
|
||||
settings: defaultSettings,
|
||||
createdAt: new Date(),
|
||||
@ -172,7 +133,7 @@ export const importTypebotInDatabase = async (
|
||||
const typebot: any = {
|
||||
...JSON.parse(readFileSync(path).toString()),
|
||||
...updates,
|
||||
ownerId: 'proUser',
|
||||
ownerId: 'user',
|
||||
}
|
||||
await prisma.typebot.create({
|
||||
data: typebot,
|
||||
|
100
apps/viewer/playwright/tests/api.spec.ts
Normal file
100
apps/viewer/playwright/tests/api.spec.ts
Normal file
@ -0,0 +1,100 @@
|
||||
import test, { expect } from '@playwright/test'
|
||||
import { createTypebots, parseDefaultBlockWithStep } from '../services/database'
|
||||
import {
|
||||
IntegrationStepType,
|
||||
defaultWebhookOptions,
|
||||
defaultWebhookAttributes,
|
||||
} from 'models'
|
||||
|
||||
const typebotId = 'webhook-flow'
|
||||
test.beforeAll(async () => {
|
||||
try {
|
||||
await createTypebots([
|
||||
{
|
||||
id: typebotId,
|
||||
...parseDefaultBlockWithStep({
|
||||
type: IntegrationStepType.WEBHOOK,
|
||||
options: defaultWebhookOptions,
|
||||
webhook: { id: 'webhookId', ...defaultWebhookAttributes },
|
||||
}),
|
||||
},
|
||||
])
|
||||
} catch (err) {}
|
||||
})
|
||||
|
||||
test('can list typebots', async ({ request }) => {
|
||||
expect((await request.get(`/api/typebots`)).status()).toBe(401)
|
||||
const response = await request.get(`/api/typebots`, {
|
||||
headers: { Authorization: 'Bearer userToken' },
|
||||
})
|
||||
const { typebots } = await response.json()
|
||||
expect(typebots).toHaveLength(1)
|
||||
expect(typebots[0]).toMatchObject({
|
||||
id: typebotId,
|
||||
publishedTypebotId: null,
|
||||
name: 'My typebot',
|
||||
})
|
||||
})
|
||||
|
||||
test('can get webhook steps', async ({ request }) => {
|
||||
expect(
|
||||
(await request.get(`/api/typebots/${typebotId}/webhookSteps`)).status()
|
||||
).toBe(401)
|
||||
const response = await request.get(
|
||||
`/api/typebots/${typebotId}/webhookSteps`,
|
||||
{
|
||||
headers: { Authorization: 'Bearer userToken' },
|
||||
}
|
||||
)
|
||||
const { steps } = await response.json()
|
||||
expect(steps).toHaveLength(1)
|
||||
expect(steps[0]).toEqual({
|
||||
stepId: 'step1',
|
||||
blockId: 'block1',
|
||||
name: 'Block #1 > step1',
|
||||
})
|
||||
})
|
||||
|
||||
test('can subscribe webhook', async ({ request }) => {
|
||||
expect(
|
||||
(
|
||||
await request.patch(
|
||||
`/api/typebots/${typebotId}/blocks/block1/steps/step1/subscribeWebhook`,
|
||||
{ data: { url: 'https://test.com' } }
|
||||
)
|
||||
).status()
|
||||
).toBe(401)
|
||||
const response = await request.patch(
|
||||
`/api/typebots/${typebotId}/blocks/block1/steps/step1/subscribeWebhook`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: 'Bearer userToken',
|
||||
},
|
||||
data: { url: 'https://test.com' },
|
||||
}
|
||||
)
|
||||
const body = await response.json()
|
||||
expect(body).toEqual({
|
||||
message: 'success',
|
||||
})
|
||||
})
|
||||
|
||||
test('can unsubscribe webhook', async ({ request }) => {
|
||||
expect(
|
||||
(
|
||||
await request.delete(
|
||||
`/api/typebots/${typebotId}/blocks/block1/steps/step1/unsubscribeWebhook`
|
||||
)
|
||||
).status()
|
||||
).toBe(401)
|
||||
const response = await request.delete(
|
||||
`/api/typebots/${typebotId}/blocks/block1/steps/step1/unsubscribeWebhook`,
|
||||
{
|
||||
headers: { Authorization: 'Bearer userToken' },
|
||||
}
|
||||
)
|
||||
const body = await response.json()
|
||||
expect(body).toEqual({
|
||||
message: 'success',
|
||||
})
|
||||
})
|
17
apps/viewer/services/api/utils.ts
Normal file
17
apps/viewer/services/api/utils.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { User } from 'db'
|
||||
import prisma from 'libs/prisma'
|
||||
import { NextApiRequest } from 'next'
|
||||
|
||||
export const authenticateUser = async (
|
||||
req: NextApiRequest
|
||||
): Promise<User | undefined> => authenticateByToken(extractBearerToken(req))
|
||||
|
||||
const authenticateByToken = async (
|
||||
apiToken?: string
|
||||
): Promise<User | undefined> => {
|
||||
if (!apiToken) return
|
||||
return (await prisma.user.findFirst({ where: { apiToken } })) as User
|
||||
}
|
||||
|
||||
const extractBearerToken = (req: NextApiRequest) =>
|
||||
req.headers['authorization']?.slice(7)
|
19
apps/viewer/services/utils.ts
Normal file
19
apps/viewer/services/utils.ts
Normal file
@ -0,0 +1,19 @@
|
||||
interface Omit {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
<T extends object, K extends [...(keyof T)[]]>(obj: T, ...keys: K): {
|
||||
[K2 in Exclude<keyof T, K[number]>]: T[K2]
|
||||
}
|
||||
}
|
||||
|
||||
export const omit: Omit = (obj, ...keys) => {
|
||||
const ret = {} as {
|
||||
[K in keyof typeof obj]: typeof obj[K]
|
||||
}
|
||||
let key: keyof typeof obj
|
||||
for (key in obj) {
|
||||
if (!keys.includes(key)) {
|
||||
ret[key] = obj[key]
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
Reference in New Issue
Block a user