fix: 🚑️ Webhook and instant updates
This commit is contained in:
@ -6,7 +6,9 @@ import { methodNotAllowed } from 'utils'
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
if (req.method === 'PUT') {
|
||||
const answer = JSON.parse(req.body) as Answer
|
||||
const answer = (
|
||||
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
|
||||
) as Answer
|
||||
const result = await prisma.answer.upsert({
|
||||
where: {
|
||||
resultId_blockId_stepId: {
|
||||
|
@ -27,8 +27,8 @@ const defaultFrom = {
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
await cors(req, res)
|
||||
if (req.method === 'POST') {
|
||||
const { credentialsId, recipients, body, subject, cc, bcc } = JSON.parse(
|
||||
req.body
|
||||
const { credentialsId, recipients, body, subject, cc, bcc } = (
|
||||
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
|
||||
) as SendEmailOptions
|
||||
|
||||
const { host, port, isTlsEnabled, username, password, from } =
|
||||
|
@ -37,7 +37,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
if (req.method === 'POST') {
|
||||
const spreadsheetId = req.query.spreadsheetId.toString()
|
||||
const sheetId = req.query.sheetId.toString()
|
||||
const { credentialsId, values } = JSON.parse(req.body) as {
|
||||
const { credentialsId, values } = (
|
||||
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
|
||||
) as {
|
||||
credentialsId: string
|
||||
values: { [key: string]: string }
|
||||
}
|
||||
@ -51,7 +53,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
if (req.method === 'PATCH') {
|
||||
const spreadsheetId = req.query.spreadsheetId.toString()
|
||||
const sheetId = req.query.sheetId.toString()
|
||||
const { credentialsId, values, referenceCell } = JSON.parse(req.body) as {
|
||||
const { credentialsId, values, referenceCell } = (
|
||||
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
|
||||
) as {
|
||||
credentialsId: string
|
||||
referenceCell: Cell
|
||||
values: { [key: string]: string }
|
||||
|
@ -6,7 +6,9 @@ import { methodNotAllowed } from 'utils'
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
if (req.method === 'POST') {
|
||||
const resultData = JSON.parse(req.body) as {
|
||||
const resultData = (
|
||||
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
|
||||
) as {
|
||||
typebotId: string
|
||||
prefilledVariables: VariableWithValue[]
|
||||
}
|
||||
|
@ -5,7 +5,9 @@ import { methodNotAllowed } from 'utils'
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
if (req.method === 'PATCH') {
|
||||
const data = JSON.parse(req.body) as { isCompleted: true }
|
||||
const data = (
|
||||
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
|
||||
) as { isCompleted: true }
|
||||
const id = req.query.id.toString()
|
||||
const result = await prisma.result.update({
|
||||
where: { id },
|
||||
|
@ -1,12 +1,21 @@
|
||||
import prisma from 'libs/prisma'
|
||||
import { KeyValue, Typebot, Variable, Webhook, WebhookResponse } from 'models'
|
||||
import {
|
||||
KeyValue,
|
||||
PublicTypebot,
|
||||
ResultValues,
|
||||
Typebot,
|
||||
Variable,
|
||||
Webhook,
|
||||
WebhookResponse,
|
||||
} from 'models'
|
||||
import { parseVariables } from 'bot-engine'
|
||||
import { NextApiRequest, NextApiResponse } from 'next'
|
||||
import got, { Method, Headers, HTTPError } from 'got'
|
||||
import { byId, initMiddleware, methodNotAllowed } from 'utils'
|
||||
import { byId, initMiddleware, methodNotAllowed, parseAnswers } from 'utils'
|
||||
import { stringify } from 'qs'
|
||||
import { withSentry } from '@sentry/nextjs'
|
||||
import Cors from 'cors'
|
||||
import { parseSampleResult } from 'services/api/webhooks'
|
||||
|
||||
const cors = initMiddleware(Cors())
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
@ -15,87 +24,125 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const typebotId = req.query.typebotId.toString()
|
||||
const blockId = req.query.blockId.toString()
|
||||
const stepId = req.query.stepId.toString()
|
||||
const variables = JSON.parse(req.body).variables as Variable[]
|
||||
const typebot = await prisma.typebot.findUnique({
|
||||
const { resultValues, variables } = (
|
||||
typeof req.body === 'string' ? JSON.parse(req.body) : req.body
|
||||
) as {
|
||||
resultValues: ResultValues | undefined
|
||||
variables: Variable[]
|
||||
}
|
||||
const typebot = (await prisma.typebot.findUnique({
|
||||
where: { id: typebotId },
|
||||
})
|
||||
const step = (typebot as unknown as Typebot).blocks
|
||||
.find(byId(blockId))
|
||||
?.steps.find(byId(stepId))
|
||||
})) as unknown as Typebot
|
||||
const step = typebot.blocks.find(byId(blockId))?.steps.find(byId(stepId))
|
||||
if (!step || !('webhook' in step))
|
||||
return res
|
||||
.status(404)
|
||||
.send({ statusCode: 404, data: { message: `Couldn't find webhook` } })
|
||||
const result = await executeWebhook(step.webhook, variables)
|
||||
const result = await executeWebhook(typebot)(
|
||||
step.webhook,
|
||||
variables,
|
||||
blockId,
|
||||
resultValues
|
||||
)
|
||||
return res.status(200).send(result)
|
||||
}
|
||||
return methodNotAllowed(res)
|
||||
}
|
||||
|
||||
const executeWebhook = async (
|
||||
webhook: Webhook,
|
||||
variables: Variable[]
|
||||
): Promise<WebhookResponse> => {
|
||||
if (!webhook.url || !webhook.method)
|
||||
return {
|
||||
statusCode: 400,
|
||||
data: { message: `Webhook doesn't have url or method` },
|
||||
}
|
||||
const basicAuth: { username?: string; password?: string } = {}
|
||||
const basicAuthHeaderIdx = webhook.headers.findIndex(
|
||||
(h) =>
|
||||
h.key?.toLowerCase() === 'authorization' &&
|
||||
h.value?.toLowerCase().includes('basic')
|
||||
)
|
||||
if (basicAuthHeaderIdx !== -1) {
|
||||
const [username, password] =
|
||||
webhook.headers[basicAuthHeaderIdx].value?.slice(6).split(':') ?? []
|
||||
basicAuth.username = username
|
||||
basicAuth.password = password
|
||||
webhook.headers.splice(basicAuthHeaderIdx, 1)
|
||||
}
|
||||
const headers = convertKeyValueTableToObject(webhook.headers, variables) as
|
||||
| Headers
|
||||
| undefined
|
||||
const queryParams = stringify(
|
||||
convertKeyValueTableToObject(webhook.queryParams, variables)
|
||||
)
|
||||
const contentType = headers ? headers['Content-Type'] : undefined
|
||||
try {
|
||||
const response = await got(
|
||||
parseVariables(variables)(webhook.url + `?${queryParams}`),
|
||||
{
|
||||
method: webhook.method as Method,
|
||||
headers,
|
||||
...basicAuth,
|
||||
json:
|
||||
contentType !== 'x-www-form-urlencoded' && webhook.body
|
||||
? JSON.parse(parseVariables(variables)(webhook.body))
|
||||
: undefined,
|
||||
form:
|
||||
contentType === 'x-www-form-urlencoded' && webhook.body
|
||||
? JSON.parse(parseVariables(variables)(webhook.body))
|
||||
: undefined,
|
||||
}
|
||||
)
|
||||
return {
|
||||
statusCode: response.statusCode,
|
||||
data: parseBody(response.body),
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof HTTPError) {
|
||||
const executeWebhook =
|
||||
(typebot: Typebot) =>
|
||||
async (
|
||||
webhook: Webhook,
|
||||
variables: Variable[],
|
||||
blockId: string,
|
||||
resultValues?: ResultValues
|
||||
): Promise<WebhookResponse> => {
|
||||
if (!webhook.url || !webhook.method)
|
||||
return {
|
||||
statusCode: error.response.statusCode,
|
||||
data: parseBody(error.response.body as string),
|
||||
statusCode: 400,
|
||||
data: { message: `Webhook doesn't have url or method` },
|
||||
}
|
||||
const basicAuth: { username?: string; password?: string } = {}
|
||||
const basicAuthHeaderIdx = webhook.headers.findIndex(
|
||||
(h) =>
|
||||
h.key?.toLowerCase() === 'authorization' &&
|
||||
h.value?.toLowerCase().includes('basic')
|
||||
)
|
||||
if (basicAuthHeaderIdx !== -1) {
|
||||
const [username, password] =
|
||||
webhook.headers[basicAuthHeaderIdx].value?.slice(6).split(':') ?? []
|
||||
basicAuth.username = username
|
||||
basicAuth.password = password
|
||||
webhook.headers.splice(basicAuthHeaderIdx, 1)
|
||||
}
|
||||
const headers = convertKeyValueTableToObject(webhook.headers, variables) as
|
||||
| Headers
|
||||
| undefined
|
||||
const queryParams = stringify(
|
||||
convertKeyValueTableToObject(webhook.queryParams, variables)
|
||||
)
|
||||
const contentType = headers ? headers['Content-Type'] : undefined
|
||||
const body = getBodyContent(typebot)({
|
||||
body: webhook.body,
|
||||
resultValues,
|
||||
blockId,
|
||||
})
|
||||
try {
|
||||
const response = await got(
|
||||
parseVariables(variables)(webhook.url + `?${queryParams}`),
|
||||
{
|
||||
method: webhook.method as Method,
|
||||
headers,
|
||||
...basicAuth,
|
||||
json:
|
||||
contentType !== 'x-www-form-urlencoded' && body
|
||||
? JSON.parse(parseVariables(variables)(body))
|
||||
: undefined,
|
||||
form:
|
||||
contentType === 'x-www-form-urlencoded' && body
|
||||
? JSON.parse(parseVariables(variables)(body))
|
||||
: undefined,
|
||||
}
|
||||
)
|
||||
return {
|
||||
statusCode: response.statusCode,
|
||||
data: parseBody(response.body),
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof HTTPError) {
|
||||
return {
|
||||
statusCode: error.response.statusCode,
|
||||
data: parseBody(error.response.body as string),
|
||||
}
|
||||
}
|
||||
console.error(error)
|
||||
return {
|
||||
statusCode: 500,
|
||||
data: { message: `Error from Typebot server: ${error}` },
|
||||
}
|
||||
}
|
||||
console.error(error)
|
||||
return {
|
||||
statusCode: 500,
|
||||
data: { message: `Error from Typebot server: ${error}` },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const getBodyContent =
|
||||
(typebot: Pick<Typebot | PublicTypebot, 'blocks' | 'variables' | 'edges'>) =>
|
||||
({
|
||||
body,
|
||||
resultValues,
|
||||
blockId,
|
||||
}: {
|
||||
body?: string
|
||||
resultValues?: ResultValues
|
||||
blockId: string
|
||||
}): string | undefined => {
|
||||
if (!body) return
|
||||
return body === '{{state}}'
|
||||
? JSON.stringify(
|
||||
resultValues
|
||||
? parseAnswers(typebot)(resultValues)
|
||||
: parseSampleResult(typebot)(blockId)
|
||||
)
|
||||
: body
|
||||
}
|
||||
|
||||
const parseBody = (body: string) => {
|
||||
try {
|
||||
|
@ -1,8 +1,9 @@
|
||||
import prisma from 'libs/prisma'
|
||||
import { Block, InputStep, InputStepType, Typebot } from 'models'
|
||||
import { Typebot } from 'models'
|
||||
import { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { authenticateUser } from 'services/api/utils'
|
||||
import { byId, isDefined, isInputStep, methodNotAllowed } from 'utils'
|
||||
import { parseSampleResult } from 'services/api/webhooks'
|
||||
import { methodNotAllowed } from 'utils'
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
if (req.method === 'GET') {
|
||||
@ -12,87 +13,11 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const blockId = req.query.blockId.toString()
|
||||
const typebot = (await prisma.typebot.findUnique({
|
||||
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
|
||||
})) as Typebot | undefined
|
||||
})) as unknown as Typebot | undefined
|
||||
if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
|
||||
const previousBlockIds = getPreviousBlocks(typebot)(blockId)
|
||||
const previousBlocks = typebot.blocks.filter((b) =>
|
||||
previousBlockIds.includes(b.id)
|
||||
)
|
||||
return res.send(parseSampleResult(typebot)(previousBlocks))
|
||||
return res.send(parseSampleResult(typebot)(blockId))
|
||||
}
|
||||
methodNotAllowed(res)
|
||||
}
|
||||
|
||||
const parseSampleResult =
|
||||
(typebot: Typebot) =>
|
||||
(blocks: Block[]): Record<string, string> => {
|
||||
const parsedBlocks = parseBlocksResultSample(typebot, blocks)
|
||||
return {
|
||||
message: 'This is a sample result, it has been generated ⬇️',
|
||||
'Submitted at': new Date().toISOString(),
|
||||
...parsedBlocks,
|
||||
...parseVariablesHeaders(typebot, parsedBlocks),
|
||||
}
|
||||
}
|
||||
|
||||
const parseBlocksResultSample = (typebot: Typebot, blocks: Block[]) =>
|
||||
blocks
|
||||
.filter((block) => typebot && block.steps.some((step) => isInputStep(step)))
|
||||
.reduce<Record<string, string>>((blocks, block) => {
|
||||
const inputStep = block.steps.find((step) => isInputStep(step))
|
||||
if (!inputStep || !isInputStep(inputStep)) return blocks
|
||||
const matchedVariableName =
|
||||
inputStep.options.variableId &&
|
||||
typebot.variables.find(byId(inputStep.options.variableId))?.name
|
||||
const value = getSampleValue(inputStep)
|
||||
return {
|
||||
...blocks,
|
||||
[matchedVariableName ?? block.title]: value,
|
||||
}
|
||||
}, {})
|
||||
|
||||
const getSampleValue = (step: InputStep) => {
|
||||
switch (step.type) {
|
||||
case InputStepType.CHOICE:
|
||||
return 'Item 1, Item 2, Item3'
|
||||
case InputStepType.DATE:
|
||||
return new Date().toUTCString()
|
||||
case InputStepType.EMAIL:
|
||||
return 'test@email.com'
|
||||
case InputStepType.NUMBER:
|
||||
return '20'
|
||||
case InputStepType.PHONE:
|
||||
return '+33665566773'
|
||||
case InputStepType.TEXT:
|
||||
return 'answer value'
|
||||
case InputStepType.URL:
|
||||
return 'https://test.com'
|
||||
}
|
||||
}
|
||||
|
||||
const parseVariablesHeaders = (
|
||||
typebot: Typebot,
|
||||
parsedBlocks: Record<string, string>
|
||||
) =>
|
||||
typebot.variables.reduce<Record<string, string>>((headers, v) => {
|
||||
if (parsedBlocks[v.name]) return headers
|
||||
return {
|
||||
...headers,
|
||||
[v.name]: 'value',
|
||||
}
|
||||
}, {})
|
||||
|
||||
const getPreviousBlocks =
|
||||
(typebot: Typebot) =>
|
||||
(blockId: string): string[] => {
|
||||
const previousBlocks = typebot.edges
|
||||
.map((edge) =>
|
||||
edge.to.blockId === blockId ? edge.from.blockId : undefined
|
||||
)
|
||||
.filter(isDefined)
|
||||
return previousBlocks.concat(
|
||||
previousBlocks.flatMap(getPreviousBlocks(typebot))
|
||||
)
|
||||
}
|
||||
|
||||
export default handler
|
||||
|
@ -18,7 +18,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const stepId = req.query.stepId.toString()
|
||||
const typebot = (await prisma.typebot.findUnique({
|
||||
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
|
||||
})) as Typebot | undefined
|
||||
})) as unknown as Typebot | undefined
|
||||
if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
|
||||
try {
|
||||
const updatedTypebot = addUrlToWebhookStep(url, typebot, stepId)
|
||||
|
@ -15,7 +15,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const stepId = req.query.stepId.toString()
|
||||
const typebot = (await prisma.typebot.findUnique({
|
||||
where: { id_ownerId: { id: typebotId, ownerId: user.id } },
|
||||
})) as Typebot | undefined
|
||||
})) as unknown as Typebot | undefined
|
||||
if (!typebot) return res.status(400).send({ message: 'Typebot not found' })
|
||||
try {
|
||||
const updatedTypebot = removeUrlFromWebhookStep(typebot, stepId)
|
||||
|
@ -20,7 +20,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
take: limit,
|
||||
include: { answers: true },
|
||||
})) as unknown as ResultWithAnswers[]
|
||||
res.send({ results: results.map(parseAnswers(typebot as Typebot)) })
|
||||
res.send({
|
||||
results: results.map(parseAnswers(typebot as unknown as Typebot)),
|
||||
})
|
||||
}
|
||||
methodNotAllowed(res)
|
||||
}
|
||||
|
Reference in New Issue
Block a user