refactor: convert UserRepository to use dependency injection pattern (#22360)
* refactor: convert UserRepository to use dependency injection pattern - Convert all static methods to public instance methods - Add constructor that takes PrismaClient parameter - Update all usage sites to use new instantiation pattern: new UserRepository(prisma).method() - Follow same pattern as PrismaOOORepository for consistency - Maintain all existing method logic and signatures unchanged - Update 125+ files across the codebase to adapt to new pattern Co-Authored-By: [email protected] <[email protected]> * optimize: reuse UserRepository instances within same function scope - Create single UserRepository instance per function scope - Reuse instance for multiple method calls within same function - Reduces object instantiation overhead and improves performance - Apply optimization pattern consistently across codebase Co-Authored-By: [email protected] <[email protected]> * fix: repository * fixup! fix: repository * fixup! fixup! fix: repository * fixup! fixup! fixup! fix: repository * fix: update test mocking strategies for UserRepository dependency injection - Convert static method mocks to instance method mocks in userCreationService.test.ts - Update vi.spyOn calls to work with constructor injection pattern in getAllCredentials.test.ts - Fix UserRepository mocking in getRoutedUrl.test.ts to use constructor injection - Ensure consistent mocking approach across all test files - Fix 'UserRepository is not a constructor' errors in tests Co-Authored-By: [email protected] <[email protected]> * feat: optimize UserRepository instance reuse and add SessionUser type - Reuse UserRepository instance in OrganizationRepository.createWithNonExistentOwner - Add comprehensive SessionUser type definition for type safety - Improve type constraints in enrichUserWithTheProfile and enrichUserWithItsProfile - Ensure proper return types with profile information Co-Authored-By: [email protected] <[email protected]> * fix: make UserRepository mocking strategy more robust for CI environments - Add defensive checks for vi.mocked() to handle CI environment differences - Ensure mockImplementation is available before calling it - Maintain consistent mocking pattern across all test files - Fix 'Cannot read properties of undefined' error in CI Co-Authored-By: [email protected] <[email protected]> * fixup! fix: make UserRepository mocking strategy more robust for CI environments * refactor: convert direct UserRepository instantiations to two-step pattern - Change await new UserRepository(prisma).method(...) to const userRepo = new UserRepository(prisma); await userRepo.method(...) - Optimize instance reuse within same function scopes - Apply pattern consistently across all modified files in PR - Fix type errors in organization.ts and sessionMiddleware.ts Co-Authored-By: [email protected] <[email protected]> * refactor: complete two-step UserRepository pattern for remaining files - Apply two-step instantiation pattern to all remaining modified files in PR - Ensure consistent UserRepository usage across entire codebase - Maintain instance reuse optimization within function scopes Co-Authored-By: [email protected] <[email protected]> * chore: bump platform libs --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: [email protected] <[email protected]> Co-authored-by: Morgan <[email protected]>
This commit is contained in:
62 files changed
+425
-209
No files matched your search
@@ -105,7 +105,9 @@ async function getHandler(req: NextApiRequest) {
|
||||
|
||||
const userIds = req.query.userId ? extractUserIdsFromQuery(req) : [userId];
|
||||
|
||||
const usersWithCalendars = await UserRepository.findManyByIdsIncludeDestinationAndSelectedCalendars({
|
||||
const usersWithCalendars = await new UserRepository(
|
||||
prisma
|
||||
).findManyByIdsIncludeDestinationAndSelectedCalendars({
|
||||
ids: userIds,
|
||||
});
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
"@axiomhq/winston": "^1.2.0",
|
||||
"@calcom/platform-constants": "*",
|
||||
"@calcom/platform-enums": "*",
|
||||
"@calcom/platform-libraries": "npm:@calcom/[email protected]49",
|
||||
"@calcom/platform-libraries": "npm:@calcom/[email protected]52",
|
||||
"@calcom/platform-types": "*",
|
||||
"@calcom/platform-utils": "*",
|
||||
"@calcom/prisma": "*",
|
||||
|
||||
@@ -4,6 +4,7 @@ import { cookies, headers } from "next/headers";
|
||||
import { getAppRegistry, getAppRegistryWithCredentials } from "@calcom/app-store/_appRegistry";
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { AppCategories } from "@calcom/prisma/enums";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
@@ -25,7 +26,8 @@ const ServerPage = async () => {
|
||||
const session = await getServerSession({ req });
|
||||
let appStore, userAdminTeamsIds: number[];
|
||||
if (session?.user?.id) {
|
||||
const userAdminTeams = await UserRepository.getUserAdminTeams(session.user.id);
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const userAdminTeams = await userRepo.getUserAdminTeams({ userId: session.user.id });
|
||||
userAdminTeamsIds = userAdminTeams?.teams?.map(({ team }) => team.id) ?? [];
|
||||
appStore = await getAppRegistryWithCredentials(session.user.id, userAdminTeamsIds);
|
||||
} else {
|
||||
|
||||
+5
-2
@@ -6,6 +6,7 @@ import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequir
|
||||
import { UsersEditView } from "@calcom/features/ee/users/pages/users-edit-view";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
const userIdSchema = z.object({ id: z.coerce.number() });
|
||||
|
||||
@@ -21,7 +22,8 @@ export const generateMetadata = async ({ params }: { params: Params }) => {
|
||||
);
|
||||
}
|
||||
|
||||
const user = await UserRepository.adminFindById(input.data.id);
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const user = await userRepo.adminFindById(input.data.id);
|
||||
|
||||
return await _generateMetadata(
|
||||
(t) => `${t("editing_user")}: ${user.username}`,
|
||||
@@ -37,7 +39,8 @@ const Page = async ({ params }: { params: Params }) => {
|
||||
|
||||
if (!input.success) throw new Error("Invalid access");
|
||||
|
||||
const user = await UserRepository.adminFindById(input.data.id);
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const user = await userRepo.adminFindById(input.data.id);
|
||||
const t = await getTranslate();
|
||||
|
||||
return (
|
||||
|
||||
@@ -11,6 +11,7 @@ import { HttpError } from "@calcom/lib/http-error";
|
||||
import notEmpty from "@calcom/lib/notEmpty";
|
||||
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
@@ -29,7 +30,10 @@ async function authMiddleware() {
|
||||
throw new HttpError({ statusCode: 401, message: "Not authenticated" });
|
||||
}
|
||||
|
||||
const userWithCredentials = await UserRepository.findUserWithCredentials({ id: session.user.id });
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const userWithCredentials = await userRepo.findUserWithCredentials({
|
||||
id: session.user.id,
|
||||
});
|
||||
|
||||
if (!userWithCredentials) {
|
||||
throw new HttpError({ statusCode: 401, message: "Not authenticated" });
|
||||
|
||||
@@ -8,6 +8,7 @@ import { z } from "zod";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { timeZoneSchema } from "@calcom/lib/dayjs/timeZone.schema";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { userMetadata } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { CardComponent } from "@lib/plain/card-components";
|
||||
@@ -474,7 +475,8 @@ async function handler(request: NextRequest) {
|
||||
// Validate request body
|
||||
const { cardKeys, customer } = inputSchema.parse(requestBody);
|
||||
|
||||
const user = await UserRepository.findByEmail({ email: customer.email });
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const user = await userRepo.findByEmail({ email: customer.email });
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({
|
||||
@@ -502,7 +504,7 @@ async function handler(request: NextRequest) {
|
||||
}
|
||||
|
||||
// Fetch team details including userId and team name
|
||||
const teamMemberships = await UserRepository.findTeamsByUserId({ userId: user.id });
|
||||
const teamMemberships = await userRepo.findTeamsByUserId({ userId: user.id });
|
||||
const firstTeam = teamMemberships.teams[0] ?? null;
|
||||
|
||||
// Parse user metadata
|
||||
|
||||
@@ -18,7 +18,8 @@ import { STEPS } from "~/apps/installation/[[...step]]/constants";
|
||||
import type { OnboardingPageProps, TEventTypeGroup } from "~/apps/installation/[[...step]]/step-view";
|
||||
|
||||
const getUser = async (userId: number) => {
|
||||
const userAdminTeams = await UserRepository.getUserAdminTeams(userId);
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const userAdminTeams = await userRepo.getUserAdminTeams({ userId });
|
||||
|
||||
if (!userAdminTeams?.id) {
|
||||
return null;
|
||||
|
||||
@@ -101,7 +101,8 @@ async function getUserPageProps(context: GetServerSidePropsContext) {
|
||||
|
||||
name = profileUsername || username;
|
||||
|
||||
const [user] = await UserRepository.findUsersByUsername({
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const [user] = await userRepo.findUsersByUsername({
|
||||
usernameList: [name],
|
||||
orgSlug: org,
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { GetServerSidePropsContext } from "next";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
export const getServerSideProps = async (context: GetServerSidePropsContext) => {
|
||||
const { req } = context;
|
||||
@@ -12,7 +13,8 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
|
||||
return { redirect: { permanent: false, destination: "/auth/login" } };
|
||||
}
|
||||
|
||||
const user = await UserRepository.findUserTeams({
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const user = await userRepo.findUserTeams({
|
||||
id: session.user.id,
|
||||
});
|
||||
|
||||
|
||||
@@ -101,8 +101,9 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
|
||||
|
||||
const eventType = booking.eventType ? booking.eventType : getDefaultEvent(dynamicEventSlugRef);
|
||||
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const enrichedBookingUser = booking.user
|
||||
? await UserRepository.enrichUserWithItsProfile({ user: booking.user })
|
||||
? await userRepo.enrichUserWithItsProfile({ user: booking.user })
|
||||
: null;
|
||||
|
||||
const eventUrl = await buildEventUrlFromBooking({
|
||||
|
||||
@@ -140,9 +140,10 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
|
||||
})
|
||||
: false;
|
||||
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const profile = booking.user
|
||||
? (
|
||||
await UserRepository.enrichUserWithItsProfile({
|
||||
await userRepo.enrichUserWithItsProfile({
|
||||
user: booking.user,
|
||||
})
|
||||
).profile
|
||||
|
||||
@@ -135,7 +135,8 @@ async function getDynamicGroupPageProps(context: GetServerSidePropsContext) {
|
||||
}
|
||||
}
|
||||
|
||||
const usersInOrgContext = await UserRepository.findUsersByUsername({
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const usersInOrgContext = await userRepo.findUsersByUsername({
|
||||
usernameList: usernames,
|
||||
orgSlug: isValidOrgDomain ? currentOrgDomain : null,
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import { stripMarkdown } from "@calcom/lib/stripMarkdown";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { RedirectType, type EventType, type User } from "@calcom/prisma/client";
|
||||
import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
import type { UserProfile } from "@calcom/types/UserProfile";
|
||||
@@ -199,7 +200,9 @@ export const getServerSideProps: GetServerSideProps<UserPageProps> = async (cont
|
||||
};
|
||||
|
||||
export async function getUsersInOrgContext(usernameList: string[], orgSlug: string | null) {
|
||||
const usersInOrgContext = await UserRepository.findUsersByUsername({
|
||||
const userRepo = new UserRepository(prisma);
|
||||
|
||||
const usersInOrgContext = await userRepo.findUsersByUsername({
|
||||
usernameList,
|
||||
orgSlug,
|
||||
});
|
||||
@@ -212,7 +215,7 @@ export async function getUsersInOrgContext(usernameList: string[], orgSlug: stri
|
||||
// the platform organization does not have a domain. In this case there is no org domain but also platform member
|
||||
// "User.organization" is not null so "UserRepository.findUsersByUsername" returns empty array and we do this as a last resort
|
||||
// call to find platform member.
|
||||
return await UserRepository.findPlatformMembersByUsernames({
|
||||
return await userRepo.findPlatformMembersByUsernames({
|
||||
usernameList,
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user