Skip to content

Commit

Permalink
feat: throw error if Prisma client is already extended with Kysely
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
eoin-obrien committed Oct 23, 2024
1 parent 357f3ec commit f826055
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,29 @@ export type PrismaKyselyExtensionArgs<Database> = {
* The Kysely instance to provide to the Prisma client
*/
// kysely: Kysely<Database>;
kysely: (driver: PrismaDriver<any>) => Kysely<Database>;
kysely: (driver: PrismaDriver<unknown>) => Kysely<Database>;
};

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 <Database>(extensionArgs: PrismaKyselyExtensionArgs<Database>) =>
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);

Expand Down
18 changes: 18 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<DB>({
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({
Expand Down

0 comments on commit f826055

Please sign in to comment.