2
0

🗃️ Write faster prisma queries

This commit is contained in:
Baptiste Arnaud
2022-12-08 11:02:52 +01:00
parent fe8a531715
commit 7eac2c7110
23 changed files with 235 additions and 134 deletions

View File

@ -1,6 +1,6 @@
import { getLinkedTypebots } from '@/features/blocks/logic/typebotLink/api'
import prisma from '@/lib/prisma'
import { canReadTypebot } from '@/utils/api/dbRules'
import { canReadTypebots } from '@/utils/api/dbRules'
import { authenticatedProcedure } from '@/utils/server/trpc'
import { TRPCError } from '@trpc/server'
import { Typebot, Webhook } from 'models'
@ -40,7 +40,7 @@ export const getResultExampleProcedure = authenticatedProcedure
)
.query(async ({ input: { typebotId, blockId }, ctx: { user } }) => {
const typebot = (await prisma.typebot.findFirst({
where: canReadTypebot(typebotId, user),
where: canReadTypebots(typebotId, user),
select: {
groups: true,
edges: true,

View File

@ -1,5 +1,5 @@
import prisma from '@/lib/prisma'
import { canReadTypebot } from '@/utils/api/dbRules'
import { canReadTypebots } from '@/utils/api/dbRules'
import { authenticatedProcedure } from '@/utils/server/trpc'
import { TRPCError } from '@trpc/server'
import { Group, Typebot, Webhook, WebhookBlock } from 'models'
@ -36,7 +36,7 @@ export const listWebhookBlocksProcedure = authenticatedProcedure
)
.query(async ({ input: { typebotId }, ctx: { user } }) => {
const typebot = (await prisma.typebot.findFirst({
where: canReadTypebot(typebotId, user),
where: canReadTypebots(typebotId, user),
select: {
groups: true,
webhooks: true,

View File

@ -1,5 +1,5 @@
import prisma from '@/lib/prisma'
import { canWriteTypebot } from '@/utils/api/dbRules'
import { canWriteTypebots } from '@/utils/api/dbRules'
import { authenticatedProcedure } from '@/utils/server/trpc'
import { TRPCError } from '@trpc/server'
import { Typebot, Webhook, WebhookBlock } from 'models'
@ -31,7 +31,7 @@ export const subscribeWebhookProcedure = authenticatedProcedure
)
.query(async ({ input: { typebotId, blockId, url }, ctx: { user } }) => {
const typebot = (await prisma.typebot.findFirst({
where: canWriteTypebot(typebotId, user),
where: canWriteTypebots(typebotId, user),
select: {
groups: true,
webhooks: true,

View File

@ -1,5 +1,5 @@
import prisma from '@/lib/prisma'
import { canWriteTypebot } from '@/utils/api/dbRules'
import { canWriteTypebots } from '@/utils/api/dbRules'
import { authenticatedProcedure } from '@/utils/server/trpc'
import { TRPCError } from '@trpc/server'
import { Typebot, Webhook, WebhookBlock } from 'models'
@ -30,7 +30,7 @@ export const unsubscribeWebhookProcedure = authenticatedProcedure
)
.query(async ({ input: { typebotId, blockId }, ctx: { user } }) => {
const typebot = (await prisma.typebot.findFirst({
where: canWriteTypebot(typebotId, user),
where: canWriteTypebots(typebotId, user),
select: {
groups: true,
webhooks: true,

View File

@ -1,5 +1,5 @@
import prisma from '@/lib/prisma'
import { canWriteTypebot } from '@/utils/api/dbRules'
import { canWriteTypebots } from '@/utils/api/dbRules'
import { deleteFiles } from '@/utils/api/storage'
import { User, Prisma } from 'db'
import { InputBlockType, Typebot } from 'models'
@ -14,7 +14,7 @@ export const archiveResults = async ({
resultsFilter?: Prisma.ResultWhereInput
}) => {
const typebot = await prisma.typebot.findFirst({
where: canWriteTypebot(typebotId, user),
where: canWriteTypebots(typebotId, user),
select: { groups: true },
})
if (!typebot) return { success: false }

View File

@ -1,4 +1,4 @@
import { canWriteTypebot } from '@/utils/api/dbRules'
import { canWriteTypebots } from '@/utils/api/dbRules'
import { authenticatedProcedure } from '@/utils/server/trpc'
import { TRPCError } from '@trpc/server'
import { z } from 'zod'
@ -34,7 +34,7 @@ export const deleteResultsProcedure = authenticatedProcedure
user,
resultsFilter: {
id: (idsArray?.length ?? 0) > 0 ? { in: idsArray } : undefined,
typebot: canWriteTypebot(typebotId, user),
typebot: canWriteTypebots(typebotId, user),
},
})

View File

@ -1,5 +1,5 @@
import prisma from '@/lib/prisma'
import { canReadTypebot } from '@/utils/api/dbRules'
import { canReadTypebots } from '@/utils/api/dbRules'
import { authenticatedProcedure } from '@/utils/server/trpc'
import { logSchema } from 'models'
import { z } from 'zod'
@ -22,9 +22,14 @@ export const getResultLogsProcedure = authenticatedProcedure
)
.output(z.object({ logs: z.array(logSchema) }))
.query(async ({ input: { typebotId, resultId }, ctx: { user } }) => {
const typebot = await prisma.typebot.findFirst({
where: canReadTypebots(typebotId, user),
select: { id: true },
})
if (!typebot) throw new Error('Typebot not found')
const logs = await prisma.log.findMany({
where: {
result: { id: resultId, typebot: canReadTypebot(typebotId, user) },
result: { id: resultId, typebotId: typebot.id },
},
})

View File

@ -1,5 +1,5 @@
import prisma from '@/lib/prisma'
import { canReadTypebot } from '@/utils/api/dbRules'
import { canReadTypebots } from '@/utils/api/dbRules'
import { authenticatedProcedure } from '@/utils/server/trpc'
import { TRPCError } from '@trpc/server'
import { ResultWithAnswers, resultWithAnswersSchema } from 'models'
@ -38,11 +38,17 @@ export const getResultsProcedure = authenticatedProcedure
message: 'limit must be between 1 and 200',
})
const { cursor } = input
const typebot = await prisma.typebot.findFirst({
where: canReadTypebots(input.typebotId, user),
select: { id: true },
})
if (!typebot)
throw new TRPCError({ code: 'NOT_FOUND', message: 'Typebot not found' })
const results = (await prisma.result.findMany({
take: limit + 1,
cursor: cursor ? { id: cursor } : undefined,
where: {
typebot: canReadTypebot(input.typebotId, user),
typebotId: typebot.id,
answers: { some: {} },
},
orderBy: {

View File

@ -2,7 +2,7 @@ import { withSentry } from '@sentry/nextjs'
import prisma from '@/lib/prisma'
import { InputBlockType, PublicTypebot } from 'models'
import { NextApiRequest, NextApiResponse } from 'next'
import { canPublishFileInput, canWriteTypebot } from '@/utils/api/dbRules'
import { canPublishFileInput, canWriteTypebots } from '@/utils/api/dbRules'
import { getAuthenticatedUser } from '@/features/auth/api'
import { badRequest, methodNotAllowed, notAuthenticated } from 'utils/api'
@ -39,7 +39,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
await prisma.publicTypebot.deleteMany({
where: {
id: publishedTypebotId,
typebot: canWriteTypebot(typebotId, user),
typebot: canWriteTypebots(typebotId, user),
},
})
return res.send({ success: true })

View File

@ -2,7 +2,7 @@ import { withSentry } from '@sentry/nextjs'
import { CollaborationType } from 'db'
import prisma from '@/lib/prisma'
import { NextApiRequest, NextApiResponse } from 'next'
import { canReadTypebot, canWriteTypebot } from '@/utils/api/dbRules'
import { canReadTypebots, canWriteTypebots } from '@/utils/api/dbRules'
import { methodNotAllowed, notAuthenticated } from 'utils/api'
import { getAuthenticatedUser } from '@/features/auth/api'
import { archiveResults } from '@/features/results/api'
@ -15,7 +15,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'GET') {
const typebot = await prisma.typebot.findFirst({
where: {
...canReadTypebot(typebotId, user),
...canReadTypebots(typebotId, user),
isArchived: { not: true },
},
include: {
@ -46,10 +46,10 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
})
if (!success) return res.status(500).send({ success: false })
await prisma.publicTypebot.deleteMany({
where: { typebot: canWriteTypebot(typebotId, user) },
where: { typebot: canWriteTypebots(typebotId, user) },
})
const typebots = await prisma.typebot.updateMany({
where: canWriteTypebot(typebotId, user),
where: canWriteTypebots(typebotId, user),
data: { isArchived: true },
})
return res.send({ typebots })
@ -57,7 +57,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'PUT') {
const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const existingTypebot = await prisma.typebot.findFirst({
where: canReadTypebot(typebotId, user),
where: canReadTypebots(typebotId, user),
select: { updatedAt: true },
})
if (
existingTypebot &&
@ -65,7 +66,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
)
return res.send({ message: 'Found newer version of typebot in database' })
const typebots = await prisma.typebot.updateMany({
where: canWriteTypebot(typebotId, user),
where: canWriteTypebots(typebotId, user),
data: {
...data,
theme: data.theme ?? undefined,
@ -78,7 +79,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'PATCH') {
const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const typebots = await prisma.typebot.updateMany({
where: canWriteTypebot(typebotId, user),
where: canWriteTypebots(typebotId, user),
data,
})
return res.send({ typebots })

View File

@ -4,7 +4,7 @@ import { NextApiRequest, NextApiResponse } from 'next'
import { methodNotAllowed, notAuthenticated } from 'utils/api'
import { withSentry } from '@sentry/nextjs'
import { getAuthenticatedUser } from '@/features/auth/api'
import { canReadTypebot } from '@/utils/api/dbRules'
import { canReadTypebots } from '@/utils/api/dbRules'
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const user = await getAuthenticatedUser(req)
@ -12,8 +12,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'GET') {
const typebotId = req.query.typebotId as string
const typebot = await prisma.typebot.findFirst({
where: canReadTypebot(typebotId, user),
include: { publishedTypebot: true },
where: canReadTypebots(typebotId, user),
select: { publishedTypebot: true },
})
const publishedTypebot =
typebot?.publishedTypebot as unknown as PublicTypebot

View File

@ -2,7 +2,7 @@ import { withSentry } from '@sentry/nextjs'
import prisma from '@/lib/prisma'
import { Stats } from 'models'
import { NextApiRequest, NextApiResponse } from 'next'
import { canReadTypebot } from '@/utils/api/dbRules'
import { canReadTypebots } from '@/utils/api/dbRules'
import { getAuthenticatedUser } from '@/features/auth/api'
import { methodNotAllowed, notAuthenticated } from 'utils/api'
@ -12,23 +12,27 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'GET') {
const typebotId = req.query.typebotId as string
const typebot = await prisma.typebot.findFirst({
where: canReadTypebots(typebotId, user),
select: { id: true },
})
if (!typebot) return res.status(404).send({ message: 'Typebot not found' })
const totalViews = await prisma.result.count({
where: {
typebotId,
typebot: canReadTypebot(typebotId, user),
typebotId: typebot.id,
},
})
const totalStarts = await prisma.result.count({
where: {
typebotId,
typebot: canReadTypebot(typebotId, user),
typebotId: typebot.id,
answers: { some: {} },
},
})
const totalCompleted = await prisma.result.count({
where: {
typebotId,
typebot: canReadTypebot(typebotId, user),
typebotId: typebot.id,
isCompleted: true,
},
})

View File

@ -1,7 +1,7 @@
import { withSentry } from '@sentry/nextjs'
import prisma from '@/lib/prisma'
import { NextApiRequest, NextApiResponse } from 'next'
import { canReadTypebot } from '@/utils/api/dbRules'
import { canReadTypebots } from '@/utils/api/dbRules'
import { getAuthenticatedUser } from '@/features/auth/api'
import { methodNotAllowed, notAuthenticated, notFound } from 'utils/api'
@ -11,7 +11,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'GET') {
const typebotId = req.query.typebotId as string
const typebot = await prisma.typebot.findFirst({
where: canReadTypebot(typebotId, user),
where: canReadTypebots(typebotId, user),
select: { groups: true },
})
if (!typebot) return notFound(res)
return res.send({ groups: typebot.groups })

View File

@ -1,7 +1,7 @@
import { withSentry } from '@sentry/nextjs'
import prisma from '@/lib/prisma'
import { NextApiRequest, NextApiResponse } from 'next'
import { canReadTypebot } from '@/utils/api/dbRules'
import { canReadTypebots } from '@/utils/api/dbRules'
import { getAuthenticatedUser } from '@/features/auth/api'
import { methodNotAllowed, notAuthenticated } from 'utils/api'
@ -11,7 +11,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const typebotId = req.query.typebotId as string
if (req.method === 'GET') {
const collaborators = await prisma.collaboratorsOnTypebots.findMany({
where: { typebot: canReadTypebot(typebotId, user) },
where: { typebot: canReadTypebots(typebotId, user) },
include: { user: { select: { name: true, image: true, email: true } } },
})
return res.send({

View File

@ -2,7 +2,7 @@ import { withSentry } from '@sentry/nextjs'
import { CollaborationType, WorkspaceRole } from 'db'
import prisma from '@/lib/prisma'
import { NextApiRequest, NextApiResponse } from 'next'
import { canReadTypebot, canWriteTypebot } from '@/utils/api/dbRules'
import { canReadTypebots, canWriteTypebots } from '@/utils/api/dbRules'
import {
badRequest,
forbidden,
@ -19,7 +19,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const typebotId = req.query.typebotId as string
if (req.method === 'GET') {
const invitations = await prisma.invitation.findMany({
where: { typebotId, typebot: canReadTypebot(typebotId, user) },
where: { typebotId, typebot: canReadTypebots(typebotId, user) },
})
return res.send({
invitations,
@ -27,7 +27,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
}
if (req.method === 'POST') {
const typebot = await prisma.typebot.findFirst({
where: canWriteTypebot(typebotId, user),
where: canWriteTypebots(typebotId, user),
include: { workspace: { select: { name: true } } },
})
if (!typebot || !typebot.workspaceId) return forbidden(res)

View File

@ -2,7 +2,7 @@ import { withSentry } from '@sentry/nextjs'
import prisma from '@/lib/prisma'
import { defaultWebhookAttributes } from 'models'
import { NextApiRequest, NextApiResponse } from 'next'
import { canWriteTypebot } from '@/utils/api/dbRules'
import { canWriteTypebots } from '@/utils/api/dbRules'
import { getAuthenticatedUser } from '@/features/auth/api'
import { forbidden, methodNotAllowed, notAuthenticated } from 'utils/api'
@ -12,7 +12,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const typebotId = req.query.typebotId as string
const typebot = await prisma.typebot.findFirst({
where: canWriteTypebot(typebotId, user),
where: canWriteTypebots(typebotId, user),
select: { id: true },
})
if (!typebot) return forbidden(res)
const webhook = await prisma.webhook.create({

View File

@ -11,21 +11,30 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const workspaceId = req.query.workspaceId as string
const now = new Date()
const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1)
const totalChatsUsed = await prisma.result.count({
where: {
typebot: {
const firstDayOfNextMonth = new Date(
now.getFullYear(),
now.getMonth() + 1,
1
)
const totalChatsUsed = await prisma.$transaction(async (tx) => {
const typebots = await tx.typebot.findMany({
where: {
workspace: {
id: workspaceId,
members: { some: { userId: user.id } },
},
},
hasStarted: true,
createdAt: {
gte: firstDayOfMonth,
lte: lastDayOfMonth,
})
return tx.result.count({
where: {
typebotId: { in: typebots.map((typebot) => typebot.id) },
hasStarted: true,
createdAt: {
gte: firstDayOfMonth,
lt: firstDayOfNextMonth,
},
},
},
})
})
const {
_sum: { storageUsed: totalStorageUsed },

View File

@ -1,50 +1,37 @@
import { CollaborationType, Plan, Prisma, User, WorkspaceRole } from 'db'
import { Plan, Prisma, User, WorkspaceRole } from 'db'
import prisma from '@/lib/prisma'
import { NextApiResponse } from 'next'
import { env, isNotEmpty } from 'utils'
import { forbidden } from 'utils/api'
const parseWhereFilter = (
export const canWriteTypebots = (
typebotIds: string[] | string,
user: User,
type: 'read' | 'write'
user: Pick<User, 'email' | 'id'>
): Prisma.TypebotWhereInput => ({
OR: [
{
id: typeof typebotIds === 'string' ? typebotIds : { in: typebotIds },
collaborators: {
some: {
userId: user.id,
type: type === 'write' ? CollaborationType.WRITE : undefined,
id: typeof typebotIds === 'string' ? typebotIds : { in: typebotIds },
workspace: isNotEmpty(env('E2E_TEST'))
? undefined
: {
members: {
some: { userId: user.id, role: { not: WorkspaceRole.GUEST } },
},
},
},
{
id: typeof typebotIds === 'string' ? typebotIds : { in: typebotIds },
workspace:
(type === 'read' && user.email === process.env.ADMIN_EMAIL) ||
isNotEmpty(env('E2E_TEST'))
? undefined
: {
members: {
some: { userId: user.id, role: { not: WorkspaceRole.GUEST } },
},
},
},
],
})
export const canReadTypebot = (typebotId: string, user: User) =>
parseWhereFilter(typebotId, user, 'read')
export const canWriteTypebot = (typebotId: string, user: User) =>
parseWhereFilter(typebotId, user, 'write')
export const canReadTypebots = (typebotIds: string[], user: User) =>
parseWhereFilter(typebotIds, user, 'read')
export const canWriteTypebots = (typebotIds: string[], user: User) =>
parseWhereFilter(typebotIds, user, 'write')
export const canReadTypebots = (
typebotIds: string | string[],
user: Pick<User, 'email' | 'id'>
) => ({
id: typeof typebotIds === 'string' ? typebotIds : { in: typebotIds },
workspace:
user.email === process.env.ADMIN_EMAIL || isNotEmpty(env('E2E_TEST'))
? undefined
: {
members: {
some: { userId: user.id },
},
},
})
export const canEditGuests = (user: User, typebotId: string) => ({
id: typebotId,