2
0

Regroup database queries of /sendMessage in one place

Potentially reduces the total queries to database and it will help to migrate to Edge runtime
This commit is contained in:
Baptiste Arnaud
2023-07-18 14:31:20 +02:00
parent 1095cf7f09
commit aa4c16dad7
32 changed files with 520 additions and 482 deletions

View File

@@ -0,0 +1,57 @@
import prisma from '@/lib/prisma'
import { isNotDefined } from '@typebot.io/lib'
import { Prisma } from '@typebot.io/prisma'
import { InputBlock, InputBlockType, SessionState } from '@typebot.io/schemas'
import got from 'got'
type Props = {
answer: Omit<Prisma.AnswerUncheckedCreateInput, 'resultId'>
block: InputBlock
reply: string
itemId?: string
state: SessionState
}
export const upsertAnswer = async ({ answer, reply, block, state }: Props) => {
if (!state.result?.id) return
if (reply.includes('http') && block.type === InputBlockType.FILE) {
answer.storageUsed = await computeStorageUsed(reply)
}
const where = {
resultId: state.result.id,
blockId: block.id,
groupId: block.groupId,
}
const existingAnswer = await prisma.answer.findUnique({
where: {
resultId_blockId_groupId: where,
},
select: { resultId: true },
})
if (existingAnswer)
return prisma.answer.updateMany({
where,
data: {
content: answer.content,
storageUsed: answer.storageUsed,
itemId: answer.itemId,
},
})
return prisma.answer.createMany({
data: [{ ...answer, resultId: state.result.id }],
})
}
const computeStorageUsed = async (reply: string) => {
let storageUsed = 0
const fileUrls = reply.split(', ')
const hasReachedStorageLimit = fileUrls[0] === null
if (!hasReachedStorageLimit) {
for (const url of fileUrls) {
const { headers } = await got(url)
const size = headers['content-length']
if (isNotDefined(size)) continue
storageUsed += parseInt(size, 10)
}
}
return storageUsed
}