feat(api): ✨ Add routes for subscribing webhook
This commit is contained in:
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