Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(prisma-adaper): update PrismaAdapter options to accept optional custom model names #12401

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 61 additions & 45 deletions packages/adapter-prisma/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,114 +15,130 @@
*
* @module @auth/prisma-adapter
*/
import type { PrismaClient, Prisma } from "@prisma/client"
import type { PrismaClient, Prisma } from "@prisma/client";
import type {
Adapter,
AdapterAccount,
AdapterSession,
AdapterUser,
} from "@auth/core/adapters"
} from "@auth/core/adapters";

export function PrismaAdapter(
prisma: PrismaClient | ReturnType<PrismaClient["$extends"]>
prisma: PrismaClient | ReturnType<PrismaClient["$extends"]>,
options?: {
accountModel?: string;
authenticatorModel?: string;
sessionModel?: string;
userModel?: string;
verificationTokenModel?: string;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just allow users to override the model name

}
): Adapter {
const p = prisma as PrismaClient
const p = prisma as PrismaClient;
const accountModel = p[options?.accountModel ?? "account"];
const authenticatorModel = p[options?.authenticatorModel ?? "authenticator"];
const sessionModel = p[options?.sessionModel ?? "session"];
const userModel = p[options?.userModel ?? "user"];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how to set up TS locally correctly, having a bunch of errors namely all args of methods have implicit any but I am not overriding the default tsconfig file afaik 🤔
Screenshot 2024-12-22 at 23 50 04

const verificationTokenModel =
p[options?.verificationTokenModel ?? "verificationToken"];
return {
// We need to let Prisma generate the ID because our default UUID is incompatible with MongoDB
createUser: ({ id, ...data }) => p.user.create(stripUndefined(data)),
getUser: (id) => p.user.findUnique({ where: { id } }),
getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
createUser: ({ id, ...data }) => userModel.create(stripUndefined(data)),
getUser: (id) => userModel.findUnique({ where: { id } }),
getUserByEmail: (email) => userModel.findUnique({ where: { email } }),
async getUserByAccount(provider_providerAccountId) {
const account = await p.account.findUnique({
const account = await accountModel.findUnique({
where: { provider_providerAccountId },
select: { user: true },
})
return (account?.user as AdapterUser) ?? null
});
return (account?.user as AdapterUser) ?? null;
},
updateUser: ({ id, ...data }) =>
p.user.update({
userModel.update({
where: { id },
...stripUndefined(data),
}) as Promise<AdapterUser>,
deleteUser: (id) =>
p.user.delete({ where: { id } }) as Promise<AdapterUser>,
userModel.delete({ where: { id } }) as Promise<AdapterUser>,
linkAccount: (data) =>
p.account.create({ data }) as unknown as AdapterAccount,
accountModel.create({ data }) as unknown as AdapterAccount,
unlinkAccount: (provider_providerAccountId) =>
p.account.delete({
accountModel.delete({
where: { provider_providerAccountId },
}) as unknown as AdapterAccount,
async getSessionAndUser(sessionToken) {
const userAndSession = await p.session.findUnique({
const userAndSession = await sessionModel.findUnique({
where: { sessionToken },
include: { user: true },
})
if (!userAndSession) return null
const { user, ...session } = userAndSession
return { user, session } as { user: AdapterUser; session: AdapterSession }
});
if (!userAndSession) return null;
const { user, ...session } = userAndSession;
return { user, session } as {
user: AdapterUser;
session: AdapterSession;
};
},
createSession: (data) => p.session.create(stripUndefined(data)),
createSession: (data) => sessionModel.create(stripUndefined(data)),
updateSession: (data) =>
p.session.update({
sessionModel.update({
where: { sessionToken: data.sessionToken },
...stripUndefined(data),
}),
deleteSession: (sessionToken) =>
p.session.delete({ where: { sessionToken } }),
sessionModel.delete({ where: { sessionToken } }),
async createVerificationToken(data) {
const verificationToken = await p.verificationToken.create(
const verificationToken = await verificationTokenModel.create(
stripUndefined(data)
)
);
// @ts-expect-errors // MongoDB needs an ID, but we don't
if (verificationToken.id) delete verificationToken.id
return verificationToken
if (verificationToken.id) delete verificationToken.id;
return verificationToken;
},
async useVerificationToken(identifier_token) {
try {
const verificationToken = await p.verificationToken.delete({
const verificationToken = await verificationTokenModel.delete({
where: { identifier_token },
})
});
// @ts-expect-errors // MongoDB needs an ID, but we don't
if (verificationToken.id) delete verificationToken.id
return verificationToken
if (verificationToken.id) delete verificationToken.id;
return verificationToken;
} catch (error) {
// If token already used/deleted, just return null
// https://www.prisma.io/docs/reference/api-reference/error-reference#p2025
if ((error as Prisma.PrismaClientKnownRequestError).code === "P2025")
return null
throw error
return null;
throw error;
}
},
async getAccount(providerAccountId, provider) {
return p.account.findFirst({
return accountModel.findFirst({
where: { providerAccountId, provider },
}) as Promise<AdapterAccount | null>
}) as Promise<AdapterAccount | null>;
},
async createAuthenticator(data) {
return p.authenticator.create(stripUndefined(data))
return authenticatorModel.create(stripUndefined(data));
},
async getAuthenticator(credentialID) {
return p.authenticator.findUnique({
return authenticatorModel.findUnique({
where: { credentialID },
})
});
},
async listAuthenticatorsByUserId(userId) {
return p.authenticator.findMany({
return authenticatorModel.findMany({
where: { userId },
})
});
},
async updateAuthenticatorCounter(credentialID, counter) {
return p.authenticator.update({
return authenticatorModel.update({
where: { credentialID },
data: { counter },
})
});
},
}
};
}

/** @see https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/null-and-undefined */
function stripUndefined<T>(obj: T) {
const data = {} as T
for (const key in obj) if (obj[key] !== undefined) data[key] = obj[key]
return { data }
const data = {} as T;
for (const key in obj) if (obj[key] !== undefined) data[key] = obj[key];
return { data };
}
Loading