feat: optimize Prisma queries by replacing findFirst with findUnique where applicable (#21826)

* feat: optimize Prisma queries by replacing findFirst with findUnique where applicable

- Replace findFirst/findFirstOrThrow with findUnique/findUniqueOrThrow for queries using unique constraints
- Maintain existing functionality and error handling behavior
- Focus on queries using primary keys and unique index fields from schema
- Revert problematic changes that caused test failures to maintain stability

Co-Authored-By: [email protected] <[email protected]>

* revert: exclude API files from Prisma query optimizations per user request

- Reverted all 55 API-related files to their original state
- Kept all non-API Prisma query optimizations intact
- API files include apps/api/v1, apps/api/v2, apps/web/app/api, and packages/app-store/*/api
- Non-API optimizations remain for packages/lib, packages/features, apps/web (non-api), etc.

Co-Authored-By: [email protected] <[email protected]>

* feat: optimize membership query in attributeUtils to use findUnique with userId_teamId constraint

Co-Authored-By: [email protected] <[email protected]>

* revert: exclude test files from Prisma query optimizations per user request

Co-Authored-By: [email protected] <[email protected]>

* revert: revert attributeUtils.ts to use findFirst for test compatibility

Co-Authored-By: [email protected] <[email protected]>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: [email protected] <[email protected]>
Co-authored-by: Anik Dhabal Babu <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-06-17 09:52:02 +03:00
1 parent a6b98bd35d
commit 4920abdaf7
93 files changed
+205 -172

No files matched your search

@@ -13,7 +13,7 @@ type DeleteOptions = {
export const deleteHandler = async ({ ctx, input }: DeleteOptions) => {
const { id } = input;
const apiKeyToDelete = await prisma.apiKey.findFirst({
const apiKeyToDelete = await prisma.apiKey.findUnique({
where: {
id,
},
@@ -77,10 +77,12 @@ const assignUserToAttributeHandler = async ({ input, ctx }: GetOptions) => {
});
}
const membership = await prisma.membership.findFirst({
const membership = await prisma.membership.findUnique({
where: {
userId: input.userId,
teamId: org.id,
userId_teamId: {
userId: input.userId,
teamId: org.id,
},
},
});
@@ -37,10 +37,12 @@ const getByUserIdHandler = async ({ input, ctx }: GetOptions) => {
}
// Ensure user is apart of the organization
const membership = await prisma.membership.findFirst({
const membership = await prisma.membership.findUnique({
where: {
userId: input.userId,
teamId: org.id,
userId_teamId: {
userId: input.userId,
teamId: org.id,
},
},
});
@@ -35,7 +35,7 @@ export const changePasswordHandler = async ({ input, ctx }: ChangePasswordOption
}
}
const currentPasswordQuery = await prisma.userPassword.findFirst({
const currentPasswordQuery = await prisma.userPassword.findUnique({
where: { userId: user.id },
});
@@ -16,7 +16,7 @@ type DeleteOptions = {
export const deleteHandler = async ({ input, ctx }: DeleteOptions) => {
const { user } = ctx;
const scheduleToDelete = await prisma.schedule.findFirst({
const scheduleToDelete = await prisma.schedule.findUnique({
where: {
id: input.scheduleId,
},
@@ -15,10 +15,12 @@ type GetOptions = {
const EMPTY_SCHEDULE = [[], [], [], [], [], [], []];
export const getScheduleByEventSlugHandler = async ({ ctx, input }: GetOptions) => {
const foundScheduleForSlug = await ctx.prisma.eventType.findFirst({
const foundScheduleForSlug = await ctx.prisma.eventType.findUnique({
where: {
slug: input.eventSlug,
userId: ctx.user.id,
userId_slug: {
userId: ctx.user.id,
slug: input.eventSlug,
},
},
select: {
scheduleId: true,
@@ -192,10 +192,12 @@ export const listTeamAvailabilityHandler = async ({ ctx, input }: GetOptions) =>
teamMembers = teamAllInfo.teamMembers;
totalTeamMembers = teamAllInfo.totalTeamMembers;
} else {
const isMember = await prisma.membership.findFirst({
const isMember = await prisma.membership.findUnique({
where: {
teamId,
userId: ctx.user.id,
userId_teamId: {
userId: ctx.user.id,
teamId,
},
},
});
@@ -23,7 +23,7 @@ export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
const { user } = ctx;
const { bookingId, guests } = input;
const booking = await prisma.booking.findFirst({
const booking = await prisma.booking.findUnique({
where: {
id: bookingId,
},
@@ -55,7 +55,7 @@ export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
throw new TRPCError({ code: "FORBIDDEN", message: "you_do_not_have_permission" });
}
const organizer = await prisma.user.findFirstOrThrow({
const organizer = await prisma.user.findUniqueOrThrow({
where: {
id: booking.userId || 0,
},
@@ -44,7 +44,7 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
const { user } = ctx;
const { bookingId, rescheduleReason: cancellationReason } = input;
log.debug("Started", safeStringify({ bookingId, cancellationReason, user }));
const bookingToReschedule = await prisma.booking.findFirstOrThrow({
const bookingToReschedule = await prisma.booking.findUniqueOrThrow({
select: {
id: true,
uid: true,
@@ -127,7 +127,7 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
let event: Partial<EventType> = {};
if (bookingToReschedule.eventTypeId) {
event = await prisma.eventType.findFirstOrThrow({
event = await prisma.eventType.findUniqueOrThrow({
select: {
title: true,
schedulingType: true,
@@ -25,7 +25,7 @@ export const getHandler = async ({ ctx }: Options) => {
},
});
const directoryId = await prisma.dSyncData.findFirst({
const directoryId = await prisma.dSyncData.findUnique({
where: {
organizationId,
},
@@ -54,10 +54,12 @@ export const duplicateHandler = async ({ ctx, input }: DuplicateOptions) => {
// Validate user is owner of event type or in the team
if (eventType.userId !== ctx.user.id) {
if (eventType.teamId) {
const isMember = await prisma.membership.findFirst({
const isMember = await prisma.membership.findUnique({
where: {
userId: ctx.user.id,
teamId: eventType.teamId,
userId_teamId: {
userId: ctx.user.id,
teamId: eventType.teamId,
},
},
});
if (!isMember) {
@@ -160,7 +160,7 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
}
if (input.completedOnboarding) {
const userTeams = await prisma.user.findFirst({
const userTeams = await prisma.user.findUnique({
where: {
id: user.id,
},
@@ -18,7 +18,7 @@ type AddClientOptions = {
export const generateAuthCodeHandler = async ({ ctx, input }: AddClientOptions) => {
const { clientId, scopes, teamSlug } = input;
const client = await prisma.oAuthClient.findFirst({
const client = await prisma.oAuthClient.findUnique({
where: {
clientId,
},
@@ -9,7 +9,7 @@ type GetClientOptions = {
export const getClientHandler = async ({ input }: GetClientOptions) => {
const { clientId } = input;
const client = await prisma.oAuthClient.findFirst({
const client = await prisma.oAuthClient.findUnique({
where: {
clientId,
},
@@ -196,7 +196,7 @@ export const outOfOfficeCreateOrUpdate = async ({ ctx, input }: TBookingRedirect
});
let resultRedirect: Prisma.OutOfOfficeEntryGetPayload<{ select: typeof selectOOOEntries }> | null = null;
if (createdOrUpdatedOutOfOffice) {
const findRedirect = await prisma.outOfOfficeEntry.findFirst({
const findRedirect = await prisma.outOfOfficeEntry.findUnique({
where: {
uuid: createdOrUpdatedOutOfOffice.uuid,
},
@@ -210,7 +210,7 @@ export const outOfOfficeCreateOrUpdate = async ({ ctx, input }: TBookingRedirect
return;
}
const toUser = toUserId
? await prisma.user.findFirst({
? await prisma.user.findUnique({
where: {
id: toUserId,
},
@@ -222,7 +222,7 @@ export const outOfOfficeCreateOrUpdate = async ({ ctx, input }: TBookingRedirect
},
})
: null;
const reason = await prisma.outOfOfficeReason.findFirst({
const reason = await prisma.outOfOfficeReason.findUnique({
where: {
id: input.reasonId,
},
@@ -233,7 +233,7 @@ export const outOfOfficeCreateOrUpdate = async ({ ctx, input }: TBookingRedirect
});
if (toUserId) {
// await send email to notify user
const userToNotify = await prisma.user.findFirst({
const userToNotify = await prisma.user.findUnique({
where: {
id: toUserId,
},
@@ -63,7 +63,7 @@ export const createTeamsHandler = async ({ ctx, input }: CreateTeamsOptions) =>
throw new NotAuthorizedError();
}
const organization = await prisma.team.findFirst({
const organization = await prisma.team.findUnique({
where: { id: orgId },
select: { slug: true, id: true, metadata: true },
});
@@ -22,7 +22,7 @@ type GetOptions = {
export const getOtherTeamHandler = async ({ input }: GetOptions) => {
// No need to validate if user is admin of org as we already do that on authedOrgAdminProcedure
const team = await prisma.team.findFirst({
const team = await prisma.team.findUnique({
where: {
id: input.teamId,
},
@@ -24,7 +24,7 @@ export async function getUserHandler({ input, ctx }: AdminVerifyOptions) {
// get requested user from database and ensure they are in the same organization
const [requestedUser, membership, teams] = await prisma.$transaction([
prisma.user.findFirst({
prisma.user.findUnique({
where: { id: input.userId },
select: {
id: true,
@@ -22,7 +22,7 @@ export const publishHandler = async ({ ctx }: PublishOptions) => {
if (!(await isOrganisationAdmin(ctx.user.id, orgId))) throw new TRPCError({ code: "UNAUTHORIZED" });
const prevTeam = await prisma.team.findFirst({
const prevTeam = await prisma.team.findUnique({
where: {
id: orgId,
},
@@ -19,7 +19,7 @@ type UpdateOptions = {
export const setPasswordHandler = async ({ ctx, input }: UpdateOptions) => {
const { newPassword } = input;
const user = await prisma.user.findFirst({
const user = await prisma.user.findUnique({
where: {
id: ctx.user.id,
},
@@ -129,7 +129,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
throw new TRPCError({ code: "CONFLICT", message: "Slug already in use." });
}
const prevOrganisation = await prisma.team.findFirst({
const prevOrganisation = await prisma.team.findUnique({
where: {
id: currentOrgId,
},
@@ -26,7 +26,7 @@ export const paymentsRouter = router({
.mutation(async ({ ctx, input }) => {
const { prisma } = ctx;
const booking = await prisma.booking.findFirstOrThrow({
const booking = await prisma.booking.findUniqueOrThrow({
where: {
id: input.bookingId,
},
@@ -19,7 +19,7 @@ interface ChargeCardHandlerOptions {
export const chargeCardHandler = async ({ ctx, input }: ChargeCardHandlerOptions) => {
const { prisma } = ctx;
const booking = await prisma.booking.findFirst({
const booking = await prisma.booking.findUnique({
where: {
id: input.bookingId,
},
@@ -87,10 +87,12 @@ export const chargeCardHandler = async ({ ctx, input }: ChargeCardHandlerOptions
: { userId: ctx.user.id };
if (booking.eventType?.teamId) {
const userIsInTeam = await prisma.membership.findFirst({
const userIsInTeam = await prisma.membership.findUnique({
where: {
userId: ctx.user.id,
teamId: booking.eventType?.teamId,
userId_teamId: {
userId: ctx.user.id,
teamId: booking.eventType?.teamId,
},
},
});
@@ -15,7 +15,7 @@ interface ResponseHandlerOptions {
export const responseHandler = async ({ ctx, input }: ResponseHandlerOptions) => {
const { prisma } = ctx;
const { formId, response, formFillerId, chosenRouteId = null, isPreview = false } = input;
const form = await prisma.app_RoutingForms_Form.findFirst({
const form = await prisma.app_RoutingForms_Form.findUnique({
where: {
id: formId,
},
@@ -42,7 +42,7 @@ export const reserveSlotHandler = async ({ ctx, input }: ReserveSlotOptions) =>
// If this is a seated event then don't reserve a slot
if (eventType.seatsPerTimeSlot) {
// Check to see if this is the last attendee
const bookingWithAttendees = await prisma.booking.findFirst({
const bookingWithAttendees = await prisma.booking.findUnique({
where: { uid: bookingUid },
select: { attendees: true },
});
@@ -59,7 +59,6 @@ export const createHandler = async ({ ctx, input }: CreateOptions) => {
const slugCollisions = await prisma.team.findFirst({
where: {
slug: slug,
// If this is under an org, check that the team doesn't already exist
parentId: isOrgChildTeam ? user.profile?.organizationId : null,
},
});
@@ -16,7 +16,7 @@ type DeleteInviteOptions = {
export const deleteInviteHandler = async ({ ctx, input }: DeleteInviteOptions) => {
const { token } = input;
const verificationToken = await prisma.verificationToken.findFirst({
const verificationToken = await prisma.verificationToken.findUnique({
where: {
token: token,
},
@@ -63,10 +63,12 @@ const checkCanUserAccessConnectedApps = async (
throw new Error("Team not found");
}
const isMember = await prisma.membership.findFirst({
const isMember = await prisma.membership.findUnique({
where: {
userId: user.id,
teamId: teamId,
userId_teamId: {
userId: user.id,
teamId: teamId,
},
},
});
@@ -29,7 +29,7 @@ export const hasActiveTeamPlanHandler = async ({ ctx }: HasActiveTeamPlanOptions
// check if user has at least on membership with an active plan
for (const team of teams) {
if (team.isPlatform && team.isOrganization) {
const platformBilling = await prisma.platformBilling.findFirst({ where: { id: team.id } });
const platformBilling = await prisma.platformBilling.findUnique({ where: { id: team.id } });
if (platformBilling && platformBilling.plan !== "none" && platformBilling.plan !== "FREE") {
return { isActive: true, isTrial: false };
}
@@ -84,7 +84,7 @@ export function checkInputEmailIsValid(email: string) {
}
export async function getTeamOrThrow(teamId: number) {
const team = await prisma.team.findFirst({
const team = await prisma.team.findUnique({
where: {
id: teamId,
},
@@ -10,7 +10,7 @@ type ListOptions = {
};
export const listOwnedTeamsHandler = async ({ ctx }: ListOptions) => {
const user = await prisma.user.findFirst({
const user = await prisma.user.findUnique({
where: {
id: ctx.user.id,
},
@@ -16,7 +16,7 @@ type SetInviteExpirationOptions = {
export const setInviteExpirationHandler = async ({ ctx, input }: SetInviteExpirationOptions) => {
const { token, expiresInDays } = input;
const verificationToken = await prisma.verificationToken.findFirst({
const verificationToken = await prisma.verificationToken.findUnique({
where: {
token: token,
},
@@ -40,7 +40,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
if (userConflict.some((t) => t.id !== input.id)) return;
}
const prevTeam = await prisma.team.findFirst({
const prevTeam = await prisma.team.findUnique({
where: {
id: input.id,
},
@@ -19,7 +19,7 @@ type EditOptions = {
export const editHandler = async ({ input, ctx }: EditOptions) => {
const { id, ...data } = input;
const webhook = await prisma.webhook.findFirst({
const webhook = await prisma.webhook.findUnique({
where: {
id,
},
@@ -18,7 +18,7 @@ export const listHandler = async ({ ctx, input }: ListOptions) => {
AND: [{ appId: !input?.appId ? null : input.appId }],
};
const user = await prisma.user.findFirst({
const user = await prisma.user.findUnique({
where: {
id: ctx.user.id,
},
@@ -29,7 +29,7 @@ export const webhookProcedure = authedProcedure
if (id) {
//check if user is authorized to edit webhook
const webhook = await prisma.webhook.findFirst({
const webhook = await prisma.webhook.findUnique({
where: {
id: id,
},
@@ -54,7 +54,7 @@ export const webhookProcedure = authedProcedure
}
if (webhook.teamId) {
const user = await prisma.user.findFirst({
const user = await prisma.user.findUnique({
where: {
id: ctx.user.id,
},
@@ -75,7 +75,7 @@ export const webhookProcedure = authedProcedure
});
}
} else if (webhook.eventTypeId) {
const eventType = await prisma.eventType.findFirst({
const eventType = await prisma.eventType.findUnique({
where: {
id: webhook.eventTypeId,
},
@@ -104,7 +104,7 @@ export const webhookProcedure = authedProcedure
} else {
//check if user is authorized to create webhook on event type or team
if (teamId) {
const user = await prisma.user.findFirst({
const user = await prisma.user.findUnique({
where: {
id: ctx.user.id,
},
@@ -119,7 +119,7 @@ export const webhookProcedure = authedProcedure
});
}
} else if (eventTypeId) {
const eventType = await prisma.eventType.findFirst({
const eventType = await prisma.eventType.findUnique({
where: {
id: eventTypeId,
},
@@ -17,7 +17,7 @@ type DeleteOptions = {
export const deleteHandler = async ({ ctx, input }: DeleteOptions) => {
const { id } = input;
const workflowToDelete = await prisma.workflow.findFirst({
const workflowToDelete = await prisma.workflow.findUnique({
where: {
id,
},
@@ -509,7 +509,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
},
});
const workflow = await ctx.prisma.workflow.findFirst({
const workflow = await ctx.prisma.workflow.findUnique({
where: {
id,
},
@@ -160,7 +160,7 @@ export const verifyEmailSender = async (email: string, userId: number, teamId: n
}
if (teamId) {
const team = await prisma.team.findFirst({
const team = await prisma.team.findUnique({
where: {
id: teamId,
},
@@ -410,7 +410,7 @@ export async function isAuthorizedToAddActiveOnIds(
) {
for (const id of newActiveIds) {
if (isOrg) {
const newTeam = await prisma.team.findFirst({
const newTeam = await prisma.team.findUnique({
where: {
id,
},
@@ -422,7 +422,7 @@ export async function isAuthorizedToAddActiveOnIds(
return false;
}
} else {
const newEventType = await prisma.eventType.findFirst({
const newEventType = await prisma.eventType.findUnique({
where: {
id,
},