2023-05-26 09:20:22 +02:00
|
|
|
import { ExecuteIntegrationResponse } from '@/features/chat/types'
|
|
|
|
import { parseVariables } from '@/features/variables/parseVariables'
|
|
|
|
import { updateVariables } from '@/features/variables/updateVariables'
|
|
|
|
import { byId } from '@typebot.io/lib'
|
|
|
|
import {
|
|
|
|
MakeComBlock,
|
|
|
|
PabblyConnectBlock,
|
|
|
|
VariableWithUnknowValue,
|
|
|
|
WebhookBlock,
|
|
|
|
ZapierBlock,
|
|
|
|
} from '@typebot.io/schemas'
|
|
|
|
import { ReplyLog, SessionState } from '@typebot.io/schemas/features/chat'
|
|
|
|
|
2023-07-18 14:31:20 +02:00
|
|
|
type Props = {
|
|
|
|
state: SessionState
|
|
|
|
block: WebhookBlock | ZapierBlock | MakeComBlock | PabblyConnectBlock
|
|
|
|
logs?: ReplyLog[]
|
|
|
|
response: {
|
2023-05-26 09:20:22 +02:00
|
|
|
statusCode: number
|
|
|
|
data?: unknown
|
2023-07-18 14:31:20 +02:00
|
|
|
}
|
|
|
|
}
|
2023-05-26 09:20:22 +02:00
|
|
|
|
2023-07-18 14:31:20 +02:00
|
|
|
export const resumeWebhookExecution = ({
|
|
|
|
state,
|
|
|
|
block,
|
|
|
|
logs = [],
|
|
|
|
response,
|
|
|
|
}: Props): ExecuteIntegrationResponse => {
|
|
|
|
const { typebot } = state
|
|
|
|
const status = response.statusCode.toString()
|
|
|
|
const isError = status.startsWith('4') || status.startsWith('5')
|
2023-05-26 09:20:22 +02:00
|
|
|
|
2023-07-18 14:31:20 +02:00
|
|
|
const responseFromClient = logs.length === 0
|
|
|
|
|
|
|
|
if (responseFromClient)
|
|
|
|
logs.push(
|
|
|
|
isError
|
|
|
|
? {
|
|
|
|
status: 'error',
|
|
|
|
description: `Webhook returned error`,
|
|
|
|
details: response.data,
|
|
|
|
}
|
|
|
|
: {
|
|
|
|
status: 'success',
|
|
|
|
description: `Webhook executed successfully!`,
|
|
|
|
details: response.data,
|
|
|
|
}
|
|
|
|
)
|
2023-05-26 09:20:22 +02:00
|
|
|
|
2023-07-18 14:31:20 +02:00
|
|
|
const newVariables = block.options.responseVariableMapping.reduce<
|
|
|
|
VariableWithUnknowValue[]
|
|
|
|
>((newVariables, varMapping) => {
|
|
|
|
if (!varMapping?.bodyPath || !varMapping.variableId) return newVariables
|
|
|
|
const existingVariable = typebot.variables.find(byId(varMapping.variableId))
|
|
|
|
if (!existingVariable) return newVariables
|
|
|
|
const func = Function(
|
|
|
|
'data',
|
|
|
|
`return data.${parseVariables(typebot.variables)(varMapping?.bodyPath)}`
|
|
|
|
)
|
|
|
|
try {
|
|
|
|
const value: unknown = func(response)
|
|
|
|
return [...newVariables, { ...existingVariable, value }]
|
|
|
|
} catch (err) {
|
|
|
|
return newVariables
|
|
|
|
}
|
|
|
|
}, [])
|
|
|
|
if (newVariables.length > 0) {
|
|
|
|
const newSessionState = updateVariables(state)(newVariables)
|
2023-05-26 09:20:22 +02:00
|
|
|
return {
|
|
|
|
outgoingEdgeId: block.outgoingEdgeId,
|
2023-07-18 14:31:20 +02:00
|
|
|
newSessionState,
|
|
|
|
logs,
|
2023-05-26 09:20:22 +02:00
|
|
|
}
|
|
|
|
}
|
2023-07-18 14:31:20 +02:00
|
|
|
|
|
|
|
return {
|
|
|
|
outgoingEdgeId: block.outgoingEdgeId,
|
|
|
|
logs,
|
|
|
|
}
|
|
|
|
}
|