2022-02-22 06:55:15 +01:00
|
|
|
import {
|
|
|
|
Typebot,
|
|
|
|
Answer,
|
|
|
|
VariableWithValue,
|
|
|
|
ResultWithAnswers,
|
|
|
|
PublicTypebot,
|
|
|
|
Block,
|
|
|
|
} from 'models'
|
2022-01-28 09:42:31 +01:00
|
|
|
import { NextApiRequest, NextApiResponse } from 'next'
|
2022-02-21 15:51:40 +01:00
|
|
|
import { byId, isDefined } from '.'
|
2021-12-06 15:48:50 +01:00
|
|
|
|
|
|
|
export const methodNotAllowed = (res: NextApiResponse) =>
|
|
|
|
res.status(405).json({ message: 'Method Not Allowed' })
|
2022-01-28 09:42:31 +01:00
|
|
|
|
|
|
|
export const initMiddleware =
|
|
|
|
(
|
|
|
|
handler: (
|
|
|
|
req: NextApiRequest,
|
|
|
|
res: NextApiResponse,
|
|
|
|
middleware: (result: any) => void
|
|
|
|
) => void
|
|
|
|
) =>
|
|
|
|
(req: any, res: any) =>
|
|
|
|
new Promise((resolve, reject) => {
|
|
|
|
handler(req, res, (result) => {
|
|
|
|
if (result instanceof Error) {
|
|
|
|
return reject(result)
|
|
|
|
}
|
|
|
|
return resolve(result)
|
|
|
|
})
|
|
|
|
})
|
2022-02-21 15:51:40 +01:00
|
|
|
|
|
|
|
export const parseAnswers =
|
2022-02-22 06:55:15 +01:00
|
|
|
({
|
|
|
|
blocks,
|
|
|
|
variables,
|
|
|
|
}: Pick<Typebot | PublicTypebot, 'blocks' | 'variables'>) =>
|
|
|
|
({
|
|
|
|
createdAt,
|
|
|
|
answers,
|
|
|
|
prefilledVariables,
|
|
|
|
}: Pick<
|
|
|
|
ResultWithAnswers,
|
|
|
|
'createdAt' | 'answers' | 'prefilledVariables'
|
|
|
|
>) => ({
|
|
|
|
submittedAt: createdAt,
|
|
|
|
...[...answers, ...prefilledVariables].reduce<{
|
2022-02-21 15:51:40 +01:00
|
|
|
[key: string]: string
|
|
|
|
}>((o, answerOrVariable) => {
|
|
|
|
if ('blockId' in answerOrVariable) {
|
|
|
|
const answer = answerOrVariable as Answer
|
|
|
|
const key = answer.variableId
|
|
|
|
? variables.find(byId(answer.variableId))?.name
|
2022-02-22 06:55:15 +01:00
|
|
|
: (blocks as Block[]).find(byId(answer.blockId))?.title
|
2022-02-21 15:51:40 +01:00
|
|
|
if (!key) return o
|
|
|
|
return {
|
|
|
|
...o,
|
|
|
|
[key]: answer.content,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
const variable = answerOrVariable as VariableWithValue
|
|
|
|
if (isDefined(o[variable.id])) return o
|
|
|
|
return { ...o, [variable.id]: variable.value }
|
|
|
|
}, {}),
|
|
|
|
})
|