2
0

🗃 Improve usage queries

This commit is contained in:
Baptiste Arnaud
2023-02-11 19:04:54 +01:00
parent c175ade4d0
commit e9a1d1683e
5 changed files with 58 additions and 46 deletions

View File

@ -18,23 +18,27 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (!typebot) return res.status(404).send({ message: 'Typebot not found' })
const totalViews = await prisma.result.count({
where: {
typebotId: typebot.id,
},
})
const totalStarts = await prisma.result.count({
where: {
typebotId: typebot.id,
answers: { some: {} },
},
})
const totalCompleted = await prisma.result.count({
where: {
typebotId: typebot.id,
isCompleted: true,
},
})
const [totalViews, totalStarts, totalCompleted] = await prisma.$transaction(
[
prisma.result.count({
where: {
typebotId: typebot.id,
},
}),
prisma.result.count({
where: {
typebotId: typebot.id,
hasStarted: true,
},
}),
prisma.result.count({
where: {
typebotId: typebot.id,
isCompleted: true,
},
}),
]
)
const stats: Stats = {
totalViews,

View File

@ -15,7 +15,12 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
now.getMonth() + 1,
1
)
const totalChatsUsed = await prisma.$transaction(async (tx) => {
const [
totalChatsUsed,
{
_sum: { storageUsed: totalStorageUsed },
},
] = await prisma.$transaction(async (tx) => {
const typebots = await tx.typebot.findMany({
where: {
workspace: {
@ -24,33 +29,30 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
},
},
})
return tx.result.count({
where: {
typebotId: { in: typebots.map((typebot) => typebot.id) },
hasStarted: true,
createdAt: {
gte: firstDayOfMonth,
lt: firstDayOfNextMonth,
},
},
})
})
const {
_sum: { storageUsed: totalStorageUsed },
} = await prisma.answer.aggregate({
where: {
storageUsed: { gt: 0 },
result: {
typebot: {
workspace: {
id: workspaceId,
members: { some: { userId: user.id } },
return Promise.all([
prisma.result.count({
where: {
typebotId: { in: typebots.map((typebot) => typebot.id) },
hasStarted: true,
createdAt: {
gte: firstDayOfMonth,
lt: firstDayOfNextMonth,
},
},
},
},
_sum: { storageUsed: true },
}),
prisma.answer.aggregate({
where: {
storageUsed: { gt: 0 },
result: {
typebotId: { in: typebots.map((typebot) => typebot.id) },
},
},
_sum: { storageUsed: true },
}),
])
})
return res.send({
totalChatsUsed,
totalStorageUsed,