Skip to content

Commit c989817

Browse files
authored
fix: more precise error code for event type duplication handler (calcom#23059)
* fix: unique constraint violation * refactor * add test * fix space * clean up
1 parent e3fb734 commit c989817

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import prismaMock from "../../../../../../tests/libs/__mocks__/prismaMock";
2+
3+
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
4+
import { describe, it, expect, vi, beforeEach } from "vitest";
5+
6+
import { TRPCError } from "@trpc/server";
7+
8+
import { duplicateHandler } from "./duplicate.handler";
9+
10+
vi.mock("@calcom/prisma", () => ({
11+
default: prismaMock,
12+
}));
13+
vi.mock("@calcom/lib/server/repository/eventTypeRepository");
14+
15+
describe("duplicateHandler", () => {
16+
const ctx = { user: { id: 1, profile: { id: 1 } } } as any;
17+
const input = { id: 123, slug: "test-event", title: "Test", description: "Test", length: 30, teamId: null };
18+
const eventType = { id: 123, userId: 1, teamId: null, users: [{ id: 1 }] };
19+
20+
beforeEach(() => {
21+
vi.resetAllMocks();
22+
prismaMock.eventType.findUnique.mockResolvedValue(eventType);
23+
});
24+
25+
it("should throw BAD_REQUEST in case of unique constraint violation", async () => {
26+
const { EventTypeRepository } = await import("@calcom/lib/server/repository/eventTypeRepository");
27+
vi.mocked(EventTypeRepository).mockImplementation(
28+
() =>
29+
({
30+
create: vi.fn().mockRejectedValue(
31+
new PrismaClientKnownRequestError("Unique constraint failed", {
32+
code: "P2002",
33+
clientVersion: "mockedVersion",
34+
})
35+
),
36+
} as any)
37+
);
38+
39+
await expect(duplicateHandler({ ctx, input })).rejects.toThrow(
40+
new TRPCError({
41+
code: "BAD_REQUEST",
42+
message: "Unique constraint violation while creating a duplicate event.",
43+
})
44+
);
45+
});
46+
});

packages/trpc/server/routers/viewer/eventTypes/duplicate.handler.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,13 @@ export const duplicateHandler = async ({ ctx, input }: DuplicateOptions) => {
226226
eventType: newEventType,
227227
};
228228
} catch (error) {
229+
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
230+
// unique constraint violation
231+
throw new TRPCError({
232+
code: "BAD_REQUEST",
233+
message: "Unique constraint violation while creating a duplicate event.",
234+
});
235+
}
229236
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `Error duplicating event type ${error}` });
230237
}
231238
};

0 commit comments

Comments
 (0)