fix: use update many for update password

This commit is contained in:
Bereket Engida
2024-11-18 15:29:23 +03:00
parent 4d9ddfce7a
commit 625ea8c040
3 changed files with 51 additions and 12 deletions

View File

@@ -187,15 +187,7 @@ export const resetPassword = createAuthEndpoint(
status: true,
});
}
const updatedUser = await ctx.context.internalAdapter.updatePassword(
userId,
hashedPassword,
);
if (!updatedUser) {
throw new APIError("BAD_REQUEST", {
message: "Failed to update password",
});
}
await ctx.context.internalAdapter.updatePassword(userId, hashedPassword);
return ctx.json({
status: true,
});

View File

@@ -24,7 +24,8 @@ export const createInternalAdapter = (
const options = ctx.options;
const secondaryStorage = options.secondaryStorage;
const sessionExpiration = options.session?.expiresIn || 60 * 60 * 24 * 7; // 7 days
const { createWithHooks, updateWithHooks } = getWithHooks(adapter, ctx);
const { createWithHooks, updateWithHooks, updateManyWithHooks } =
getWithHooks(adapter, ctx);
return {
createOAuthUser: async (
user: Omit<User, "id" | "createdAt" | "updatedAt"> & Partial<User>,
@@ -580,7 +581,7 @@ export const createInternalAdapter = (
return user;
},
updatePassword: async (userId: string, password: string) => {
const account = await updateWithHooks<Account>(
await updateManyWithHooks(
{
password,
},
@@ -596,7 +597,6 @@ export const createInternalAdapter = (
],
"account",
);
return account;
},
findAccounts: async (userId: string) => {
const accounts = await adapter.findMany<Account>({

View File

@@ -99,8 +99,55 @@ export function getWithHooks(
return updated;
}
async function updateManyWithHooks<T extends Record<string, any>>(
data: any,
where: Where[],
model: Models,
customUpdateFn?: {
fn: (data: Record<string, any>) => void | Promise<any>;
executeMainFn?: boolean;
},
) {
let actualData = data;
for (const hook of hooks || []) {
const toRun = hook[model]?.update?.before;
if (toRun) {
const result = await toRun(data as any);
if (result === false) {
return null;
}
const isObject = typeof result === "object";
actualData = isObject ? (result as any).data : result;
}
}
const customUpdated = customUpdateFn
? await customUpdateFn.fn(actualData)
: null;
const updated =
!customUpdateFn || customUpdateFn.executeMainFn
? await adapter.updateMany({
model,
update: actualData,
where,
})
: customUpdated;
for (const hook of hooks || []) {
const toRun = hook[model]?.update?.after;
if (toRun) {
await toRun(updated as any);
}
}
return updated;
}
return {
createWithHooks,
updateWithHooks,
updateManyWithHooks,
};
}