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

Optimizar proceso de creación/actualización de usuarios y resolver race condition #271

Merged
merged 1 commit into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 2 additions & 2 deletions src/authn/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ORM_TYPE } from "~/datasources/db";
import { insertUsersSchema, USER } from "~/datasources/db/schema";
import {
findUserByID,
updateUserProfileInfo,
upsertUserProfileInfo,
} from "~/datasources/queries/users";
import { getUsername } from "~/datasources/queries/utils/createUsername";
import { unauthorizedError } from "~/errors";
Expand Down Expand Up @@ -141,7 +141,7 @@ export const upsertUserFromRequest = async ({

logger.info(`Updating profile Info for user ID: ${sub}`);

return updateUserProfileInfo(DB, profileInfo.data, logger);
return upsertUserProfileInfo(DB, profileInfo.data, logger);
};

export const logPossibleUserIdFromJWT = (request: Request, logger: Logger) => {
Expand Down
76 changes: 33 additions & 43 deletions src/datasources/queries/users.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { eq } from "drizzle-orm";
import { z } from "zod";

import { ORM_TYPE } from "~/datasources/db";
Expand All @@ -20,64 +19,55 @@ export const findUserByID = async (db: ORM_TYPE, id: string) => {
return result ? selectUsersSchema.parse(result) : null;
};

export const updateUserProfileInfo = async (
export const upsertUserProfileInfo = async (
db: ORM_TYPE,
parsedProfileInfo: z.infer<typeof insertUsersSchema>,
logger: Logger,
) => {
const result = await db.query.usersSchema.findFirst({
where: (u, { eq }) => eq(u.email, parsedProfileInfo.email.toLowerCase()),
});
logger.info(
`Upserting user profile info for ${parsedProfileInfo.email} (externalId: ${
parsedProfileInfo.externalId || "N/A"
})`,
);

const { email, externalId, name, imageUrl, isEmailVerified, publicMetadata } =
parsedProfileInfo;
const lowercaseEmail = email.trim().toLowerCase();

const upsertData: z.infer<typeof allowedUserUpdateForAuth> = {
externalId,
name,
imageUrl,
isEmailVerified,
publicMetadata: publicMetadata ?? {},
status: UserStatusEnum.active,
};

if (!result) {
logger.info("User not found — creating new user");
// we create the user
const createdUsers = await db
try {
const result = await db
.insert(usersSchema)
.values({
externalId: parsedProfileInfo.externalId,
email: parsedProfileInfo.email.trim().toLowerCase(),
...upsertData,
email: lowercaseEmail,
username: parsedProfileInfo.username ?? getUsername(),
name: parsedProfileInfo.name,
imageUrl: parsedProfileInfo.imageUrl,
isEmailVerified: parsedProfileInfo.isEmailVerified,
publicMetadata: parsedProfileInfo.publicMetadata ?? {},
status: UserStatusEnum.active,
})
.onConflictDoUpdate({
target: usersSchema.email,
set: allowedUserUpdateForAuth.parse(upsertData),
})
.returning();
const createdUser = createdUsers?.[0];

if (!createdUser) {
logger.error("Could not create user");
throw new Error("Could not create user");
}

return selectUsersSchema.parse(createdUser);
} else {
logger.info("User found — updating user");
// we update the user
const updateData = allowedUserUpdateForAuth.parse({
externalId: parsedProfileInfo.externalId,
name: parsedProfileInfo.name,
imageUrl: parsedProfileInfo.imageUrl,
isEmailVerified: parsedProfileInfo.isEmailVerified,
publicMetadata: parsedProfileInfo.publicMetadata ?? {},
status: UserStatusEnum.active,
});
const updatedUsers = await db
.update(usersSchema)
.set(updateData)
.where(eq(usersSchema.email, parsedProfileInfo.email))
.returning();
const updatedUser = updatedUsers?.[0];
const updatedUser = result[0];

if (!updatedUser) {
logger.error("Could not update user");
throw new Error("Could not update user");
throw new Error("User operation failed");
}

logger.info("User updated");
logger.info(result.length > 1 ? "User updated" : "New user created");

return selectUsersSchema.parse(updatedUser);
} catch (error) {
logger.error("Error in user operation", { error });
throw new Error("User operation failed");
}
};
Loading