refactor: simplify user update logic in Clerk webhook handler to reuse findOrCreateUser
This commit is contained in:
parent
8c73f7172a
commit
7729da9cc8
1 changed files with 10 additions and 23 deletions
|
|
@ -1,6 +1,6 @@
|
||||||
import { Webhook } from "svix";
|
import { Webhook } from "svix";
|
||||||
import type { Route } from "./+types/clerk";
|
import type { Route } from "./+types/clerk";
|
||||||
import { findOrCreateUser, updateUserByClerkId } from "~/models/user";
|
import { findOrCreateUser } from "~/models/user";
|
||||||
|
|
||||||
export async function action({ request }: Route.ActionArgs) {
|
export async function action({ request }: Route.ActionArgs) {
|
||||||
// Get the webhook secret from environment
|
// Get the webhook secret from environment
|
||||||
|
|
@ -65,29 +65,16 @@ export async function action({ request }: Route.ActionArgs) {
|
||||||
`User created in database: ${user.id} (${user.username || user.displayName})`
|
`User created in database: ${user.id} (${user.username || user.displayName})`
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// Update existing user
|
// Update existing user (or create if doesn't exist)
|
||||||
const email = email_addresses?.[0]?.email_address;
|
const user = await findOrCreateUser({
|
||||||
if (!email) {
|
id,
|
||||||
throw new Error("User must have an email address");
|
emailAddresses:
|
||||||
}
|
email_addresses?.map((e: any) => ({
|
||||||
|
emailAddress: e.email_address,
|
||||||
// Generate display name
|
})) || [],
|
||||||
let displayName = "";
|
|
||||||
if (first_name || last_name) {
|
|
||||||
displayName = [first_name, last_name]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(" ")
|
|
||||||
.trim();
|
|
||||||
} else {
|
|
||||||
displayName = email.split("@")[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await updateUserByClerkId(id, {
|
|
||||||
email,
|
|
||||||
username,
|
username,
|
||||||
displayName,
|
firstName: first_name,
|
||||||
firstName: first_name || undefined,
|
lastName: last_name,
|
||||||
lastName: last_name || undefined,
|
|
||||||
imageUrl: image_url,
|
imageUrl: image_url,
|
||||||
});
|
});
|
||||||
console.log(
|
console.log(
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue