From f8260559fdddf28a3d587e10d6cff25fe38467a4 Mon Sep 17 00:00:00 2001 From: Eoin O'Brien Date: Wed, 23 Oct 2024 02:39:24 +0100 Subject: [PATCH] feat: throw error if Prisma client is already extended with Kysely Added a check to throw an error if the Prisma client is already extended with Kysely. This change prevents undefined behavior and ensures that the client is not extended multiple times. Introduced a new test case to validate this behavior. BREAKING CHANGE: This change introduces an error where previously there was none, which may affect existing code that accidentally extended the Prisma client multiple times. --- src/index.ts | 16 +++++++++++++++- test/index.test.ts | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 1e36300..accdc45 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,15 +11,29 @@ export type PrismaKyselyExtensionArgs = { * The Kysely instance to provide to the Prisma client */ // kysely: Kysely; - kysely: (driver: PrismaDriver) => Kysely; + kysely: (driver: PrismaDriver) => Kysely; }; +export class PrismaKyselyExtensionError extends Error { + constructor(message: string) { + super(message); + this.name = "PrismaKyselyExtensionError"; + } +} + /** * Define a Prisma extension that adds Kysely query builder methods to the Prisma client * @param extensionArgs The extension configuration object */ export default (extensionArgs: PrismaKyselyExtensionArgs) => Prisma.defineExtension((client) => { + // Check if the client is already extended + if ("$kysely" in client) { + throw new PrismaKyselyExtensionError( + "The Prisma client is already extended with Kysely", + ); + } + const driver = new PrismaDriver(client); const kysely = extensionArgs.kysely(driver); diff --git a/test/index.test.ts b/test/index.test.ts index 1cf7c00..76a27e4 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -209,6 +209,24 @@ describe("prisma-extension-kysely", () => { ); }); + it("should throw an error if the Prisma client is already extended with Kysely", async () => { + expect(() => + xprisma.$extends( + kyselyExtension({ + kysely: (driver) => + new Kysely({ + dialect: { + createAdapter: () => new SqliteAdapter(), + createDriver: () => driver, + createIntrospector: (db) => new SqliteIntrospector(db), + createQueryCompiler: () => new SqliteQueryCompiler(), + }, + }), + }), + ), + ).toThrow("The Prisma client is already extended with Kysely"); + }); + describe("@prisma/extension-read-replicas", () => { const replica = new PrismaClient().$extends( kyselyExtension({