Skip to content

Commit

Permalink
⚡ Regroup database queries of /sendMessage in one place
Browse files Browse the repository at this point in the history
Potentially reduces the total queries to database and it will help to migrate to Edge runtime
  • Loading branch information
baptisteArno committed Jul 18, 2023
1 parent 1095cf7 commit aa4c16d
Show file tree
Hide file tree
Showing 32 changed files with 520 additions and 482 deletions.
2 changes: 1 addition & 1 deletion apps/builder/src/features/templates/templates.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ test.describe.parallel('Templates page', () => {
await page.click('text=Customer Support')
await expect(page.locator('text=How can I help you?')).toBeVisible()
await page.click('text=Use this template')
await expect(page).toHaveURL(new RegExp(`/edit`), { timeout: 10000 })
await expect(page).toHaveURL(new RegExp(`/edit`), { timeout: 20000 })
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ import { filterChoiceItems } from './filterChoiceItems'

export const injectVariableValuesInButtonsInputBlock =
(state: SessionState) =>
async (block: ChoiceInputBlock): Promise<ChoiceInputBlock> => {
(block: ChoiceInputBlock): ChoiceInputBlock => {
if (block.options.dynamicVariableId) {
const variable = state.typebot.variables.find(
(variable) =>
variable.id === block.options.dynamicVariableId &&
isDefined(variable.value)
) as VariableWithValue | undefined
if (!variable) return block
const value = await getVariableValue(state)(variable)
const value = getVariableValue(state)(variable)
return {
...block,
items: value.filter(isDefined).map((item, idx) => ({
Expand All @@ -38,12 +38,12 @@ export const injectVariableValuesInButtonsInputBlock =

const getVariableValue =
(state: SessionState) =>
async (variable: VariableWithValue): Promise<(string | null)[]> => {
(variable: VariableWithValue): (string | null)[] => {
if (!Array.isArray(variable.value)) {
const [transformedVariable] = transformStringVariablesToList(
state.typebot.variables
)([variable.id])
await updateVariables(state)([transformedVariable])
updateVariables(state)([transformedVariable])
return transformedVariable.value as string[]
}
return variable.value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ import {
import { isNotEmpty, byId } from '@typebot.io/lib'
import { getAuthenticatedGoogleDoc } from './helpers/getAuthenticatedGoogleDoc'
import { ExecuteIntegrationResponse } from '@/features/chat/types'
import { saveErrorLog } from '@/features/logs/saveErrorLog'
import { updateVariables } from '@/features/variables/updateVariables'
import { deepParseVariables } from '@/features/variables/deepParseVariable'
import { matchFilter } from './helpers/matchFilter'
import { saveInfoLog } from '@/features/logs/saveInfoLog'

export const getRow = async (
state: SessionState,
Expand All @@ -20,15 +18,13 @@ export const getRow = async (
options,
}: { outgoingEdgeId?: string; options: GoogleSheetsGetOptions }
): Promise<ExecuteIntegrationResponse> => {
const logs: ReplyLog[] = []
const { sheetId, cellsToExtract, referenceCell, filter } = deepParseVariables(
state.typebot.variables
)(options)
if (!sheetId) return { outgoingEdgeId }

let log: ReplyLog | undefined

const variables = state.typebot.variables
const resultId = state.result?.id

const doc = await getAuthenticatedGoogleDoc({
credentialsId: options.credentialsId,
Expand All @@ -48,16 +44,12 @@ export const getRow = async (
)
)
if (filteredRows.length === 0) {
log = {
logs.push({
status: 'info',
description: `Couldn't find any rows matching the filter`,
details: JSON.stringify(filter, null, 2),
}
await saveInfoLog({
resultId,
message: log.description,
})
return { outgoingEdgeId, logs: log ? [log] : undefined }
return { outgoingEdgeId, logs }
}
const extractingColumns = cellsToExtract
.map((cell) => cell.column)
Expand Down Expand Up @@ -85,24 +77,19 @@ export const getRow = async (
},
[]
)
const newSessionState = await updateVariables(state)(newVariables)
const newSessionState = updateVariables(state)(newVariables)
return {
outgoingEdgeId,
newSessionState,
}
} catch (err) {
log = {
logs.push({
status: 'error',
description: `An error occurred while fetching the spreadsheet data`,
details: err,
}
await saveErrorLog({
resultId,
message: log.description,
details: err,
})
}
return { outgoingEdgeId, logs: log ? [log] : undefined }
return { outgoingEdgeId, logs }
}

const getTotalRows = <T>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,17 @@ import {
import { parseCellValues } from './helpers/parseCellValues'
import { getAuthenticatedGoogleDoc } from './helpers/getAuthenticatedGoogleDoc'
import { ExecuteIntegrationResponse } from '@/features/chat/types'
import { saveErrorLog } from '@/features/logs/saveErrorLog'
import { saveSuccessLog } from '@/features/logs/saveSuccessLog'

export const insertRow = async (
{ result, typebot: { variables } }: SessionState,
{ typebot: { variables } }: SessionState,
{
outgoingEdgeId,
options,
}: { outgoingEdgeId?: string; options: GoogleSheetsInsertRowOptions }
): Promise<ExecuteIntegrationResponse> => {
if (!options.cellsToInsert || !options.sheetId) return { outgoingEdgeId }

let log: ReplyLog | undefined
const logs: ReplyLog[] = []

const doc = await getAuthenticatedGoogleDoc({
credentialsId: options.credentialsId,
Expand All @@ -31,27 +29,17 @@ export const insertRow = async (
await doc.loadInfo()
const sheet = doc.sheetsById[Number(options.sheetId)]
await sheet.addRow(parsedValues)
log = {
logs.push({
status: 'success',
description: `Succesfully inserted row in ${doc.title} > ${sheet.title}`,
}
result &&
(await saveSuccessLog({
resultId: result.id,
message: log?.description,
}))
})
} catch (err) {
log = {
logs.push({
status: 'error',
description: `An error occured while inserting the row`,
details: err,
}
result &&
(await saveErrorLog({
resultId: result.id,
message: log.description,
details: err,
}))
})
}
return { outgoingEdgeId, logs: log ? [log] : undefined }

return { outgoingEdgeId, logs }
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,10 @@ import { parseCellValues } from './helpers/parseCellValues'
import { getAuthenticatedGoogleDoc } from './helpers/getAuthenticatedGoogleDoc'
import { deepParseVariables } from '@/features/variables/deepParseVariable'
import { ExecuteIntegrationResponse } from '@/features/chat/types'
import { saveErrorLog } from '@/features/logs/saveErrorLog'
import { saveSuccessLog } from '@/features/logs/saveSuccessLog'
import { matchFilter } from './helpers/matchFilter'
import { saveInfoLog } from '@/features/logs/saveInfoLog'

export const updateRow = async (
{ result, typebot: { variables } }: SessionState,
{ typebot: { variables } }: SessionState,
{
outgoingEdgeId,
options,
Expand All @@ -24,7 +21,7 @@ export const updateRow = async (
if (!options.cellsToUpsert || !sheetId || (!referenceCell && !filter))
return { outgoingEdgeId }

let log: ReplyLog | undefined
const logs: ReplyLog[] = []

const doc = await getAuthenticatedGoogleDoc({
credentialsId: options.credentialsId,
Expand All @@ -42,18 +39,12 @@ export const updateRow = async (
: matchFilter(row, filter as NonNullable<typeof filter>)
)
if (filteredRows.length === 0) {
log = {
logs.push({
status: 'info',
description: `Could not find any row that matches the filter`,
details: JSON.stringify(filter, null, 2),
}
result &&
(await saveInfoLog({
resultId: result.id,
message: log.description,
details: log.details,
}))
return { outgoingEdgeId, logs: log ? [log] : undefined }
details: filter,
})
return { outgoingEdgeId, logs }
}

try {
Expand All @@ -65,28 +56,17 @@ export const updateRow = async (
await rows[rowIndex].save()
}

log = log = {
logs.push({
status: 'success',
description: `Succesfully updated matching rows`,
}
result &&
(await saveSuccessLog({
resultId: result.id,
message: log.description,
}))
})
} catch (err) {
console.log(err)
log = {
logs.push({
status: 'error',
description: `An error occured while updating the row`,
details: err,
}
result &&
(await saveErrorLog({
resultId: result.id,
message: log.description,
details: err,
}))
})
}
return { outgoingEdgeId, logs: log ? [log] : undefined }
return { outgoingEdgeId, logs }
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export const createChatCompletionOpenAI = async (
newSessionState.typebot.variables
)(options.messages)
if (variablesTransformedToList.length > 0)
newSessionState = await updateVariables(state)(variablesTransformedToList)
newSessionState = updateVariables(state)(variablesTransformedToList)

const temperature = parseVariableNumber(newSessionState.typebot.variables)(
options.advancedSettings?.temperature
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export const executeChatCompletionOpenAIRequest = async ({
logs.push({
status: 'error',
description: `Internal error`,
details: error,
})
return { logs }
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { saveSuccessLog } from '@/features/logs/saveSuccessLog'
import { updateVariables } from '@/features/variables/updateVariables'
import { byId, isDefined } from '@typebot.io/lib'
import { ChatReply, SessionState } from '@typebot.io/schemas'
Expand All @@ -11,7 +10,7 @@ export const resumeChatCompletion =
{
outgoingEdgeId,
options,
logs,
logs = [],
}: {
outgoingEdgeId?: string
options: ChatCompletionOpenAIOptions
Expand Down Expand Up @@ -44,12 +43,11 @@ export const resumeChatCompletion =
return newVariables
}, [])
if (newVariables.length > 0)
newSessionState = await updateVariables(newSessionState)(newVariables)
state.result &&
(await saveSuccessLog({
resultId: state.result.id,
message: 'OpenAI block successfully executed',
}))
newSessionState = updateVariables(newSessionState)(newVariables)
logs.push({
description: 'OpenAI block successfully executed',
status: 'success',
})
return {
outgoingEdgeId,
newSessionState,
Expand Down
Loading

4 comments on commit aa4c16d

@vercel
Copy link

@vercel vercel bot commented on aa4c16d Jul 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

docs – ./apps/docs

docs-git-main-typebot-io.vercel.app
docs-typebot-io.vercel.app
docs.typebot.io

@vercel
Copy link

@vercel vercel bot commented on aa4c16d Jul 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on aa4c16d Jul 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

builder-v2 – ./apps/builder

app.typebot.io
builder-v2-typebot-io.vercel.app
builder-v2-git-main-typebot-io.vercel.app

@vercel
Copy link

@vercel vercel bot commented on aa4c16d Jul 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

viewer-v2 – ./apps/viewer

amancarseat.online
amostra-safe.click
andreimayer.com.br
bebesemcolicas.com
bot.danyservice.it
bot.iconicbrows.it
bot.lucide.contact
bot.neferlopez.com
bot.samplehunt.com
bot.sinalcerto.com
bot.wphelpchat.com
bots.robomotion.io
cadu.uninta.edu.br
chat.hand-made.one
chat.tuanpakya.com
chat.webisharp.com
descobrindotudo.me
dicanatural.online
digitalhelp.com.au
draraquelnutri.com
goalsettingbot.com
leads.gecoelho.com
noticiasnet.online
novoappespiao.site
omarcodosanjos.com
pant.maxbot.com.br
pantherview.cr8.ai
positivobra.com.br
rollingball.cr8.ai
secretmezcla.space
speciallife.com.br
sub.yolozeeeer.com
survey.digienge.io
zap.techadviser.in
ai.digitaldaftar.in
app.danielnalex.com
ask.realversity.org
bot.boston-voip.com
bot.cabinpromos.com
bot.carnaval.studio
bot.digitalbled.com
bot.dsignagency.com
bot.enthrallart.com
bot.eventhub.com.au
bot.gravityatoms.in
bot.jepierre.com.br
bot.leadgenpod.site
bot.synapsegameia.com
bot.truongnguyen.live
bots.baptistearno.com
botz.cloudsiteapp.com
cdd.searchcube.com.sg
chat.missarkansas.org
chatbot.ownacademy.co
chats.maisefetivo.com
claudio-barros.online
criar.somaperuzzo.com
gotasafrodisiacas.com
homerun.wpwakanda.com
mdb.assessoria.ademir
portaldasanalises.com
revistasaudeemdia.com
sbutton.wpwakanda.com
viewer-v2-typebot-io.vercel.app
mdb.assessoria.jbatista.progenbr.com
mdb.assessoria.mauricio.progenbr.com
form.shopmercedesbenzsouthorlando.com
mdb.evento.equipeinterna.progenbr.com
bot.studiotecnicoimmobiliaremerelli.it
mdb.assessoria.boaventura.progenbr.com
mdb.assessoria.jtrebesqui.progenbr.com
pesquisa.escolamodacomproposito.com.br
anamnese.clinicaramosodontologia.com.br
gabinete.baleia.formulario.progenbr.com
mdb.assessoria.carreirinha.progenbr.com
chrome-os-inquiry-system.itschromeos.com
mdb.assessoria.paulomarques.progenbr.com
viewer-v2-git-main-typebot-io.vercel.app
main-menu-for-itschromeos.itschromeos.com
mdb.assessoria.qrcode.ademir.progenbr.com
mdb.assessoria.qrcode.arthur.progenbr.com
mdb.assessoria.qrcode.danilo.progenbr.com
mdb.assessoria.qrcode.marcao.progenbr.com
mdb.assessoria.qrcode.marcio.progenbr.com
mdb.assessoria.qrcode.aloisio.progenbr.com
mdb.assessoria.qrcode.girotto.progenbr.com
mdb.assessoria.qrcode.marinho.progenbr.com
mdb.assessoria.qrcode.rodrigo.progenbr.com
mdb.assessoria.carlosalexandre.progenbr.com
mdb.assessoria.qrcode.desideri.progenbr.com
mdb.assessoria.qrcode.fernanda.progenbr.com
mdb.assessoria.qrcode.jbatista.progenbr.com
mdb.assessoria.qrcode.mauricio.progenbr.com
mdb.assessoria.fernanda.regional.progenbr.com
mdb.assessoria.qrcode.boaventura.progenbr.com
mdb.assessoria.qrcode.jtrebesqui.progenbr.com
mdb.assessoria.qrcode.carreirinha.progenbr.com
mdb.assessoria.qrcode.paulomarques.progenbr.com
mdb.assessoria.qrcode.carlosalexandre.progenbr.com
mdb.assessoria.qrcode.fernanda.regional.progenbr.com

Please sign in to comment.