2023-03-15 08:35:16 +01:00
|
|
|
import { SessionState, SetVariableBlock, Variable } from '@typebot.io/schemas'
|
|
|
|
import { byId } from '@typebot.io/lib'
|
2023-03-15 12:21:52 +01:00
|
|
|
import { ExecuteLogicResponse } from '@/features/chat/types'
|
|
|
|
import { updateVariables } from '@/features/variables/updateVariables'
|
|
|
|
import { parseVariables } from '@/features/variables/parseVariables'
|
|
|
|
import { parseGuessedValueType } from '@/features/variables/parseGuessedValueType'
|
2022-11-29 10:02:40 +01:00
|
|
|
|
|
|
|
export const executeSetVariable = async (
|
|
|
|
state: SessionState,
|
|
|
|
block: SetVariableBlock
|
|
|
|
): Promise<ExecuteLogicResponse> => {
|
|
|
|
const { variables } = state.typebot
|
|
|
|
if (!block.options?.variableId)
|
|
|
|
return {
|
|
|
|
outgoingEdgeId: block.outgoingEdgeId,
|
|
|
|
}
|
|
|
|
const evaluatedExpression = block.options.expressionToEvaluate
|
|
|
|
? evaluateSetVariableExpression(variables)(
|
|
|
|
block.options.expressionToEvaluate
|
|
|
|
)
|
|
|
|
: undefined
|
|
|
|
const existingVariable = variables.find(byId(block.options.variableId))
|
|
|
|
if (!existingVariable) return { outgoingEdgeId: block.outgoingEdgeId }
|
|
|
|
const newVariable = {
|
|
|
|
...existingVariable,
|
|
|
|
value: evaluatedExpression,
|
|
|
|
}
|
|
|
|
const newSessionState = await updateVariables(state)([newVariable])
|
|
|
|
return {
|
|
|
|
outgoingEdgeId: block.outgoingEdgeId,
|
|
|
|
newSessionState,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const evaluateSetVariableExpression =
|
|
|
|
(variables: Variable[]) =>
|
|
|
|
(str: string): unknown => {
|
2023-02-22 12:21:11 +01:00
|
|
|
const isSingleVariable =
|
|
|
|
str.startsWith('{{') && str.endsWith('}}') && str.split('{{').length === 2
|
|
|
|
if (isSingleVariable) return parseVariables(variables)(str)
|
2022-11-29 10:02:40 +01:00
|
|
|
const evaluating = parseVariables(variables, { fieldToParse: 'id' })(
|
|
|
|
str.includes('return ') ? str : `return ${str}`
|
|
|
|
)
|
|
|
|
try {
|
|
|
|
const func = Function(...variables.map((v) => v.id), evaluating)
|
2023-03-15 12:21:52 +01:00
|
|
|
return func(...variables.map((v) => parseGuessedValueType(v.value)))
|
2022-11-29 10:02:40 +01:00
|
|
|
} catch (err) {
|
2023-02-16 10:19:11 +01:00
|
|
|
return parseVariables(variables)(str)
|
2022-11-29 10:02:40 +01:00
|
|
|
}
|
|
|
|
}
|