-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathregister-user.ts
More file actions
45 lines (39 loc) · 1.41 KB
/
register-user.ts
File metadata and controls
45 lines (39 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import User from "~/interfaces/User";
import { getMessage, mongo } from "~/server";
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const { data, type } = body;
const theEmail = type === "user.created" ? data.email_addresses[0].email_address : "";
try {
let theUser =
type === "user.created" ?
await mongo.findUserByEmail(theEmail) :
type === "session.created" ?
await mongo.findUserByClerkId(data.user_id) :
undefined;
if (theUser === null) {
// The newly registered or signed in user is not yet in the db
const userDetails: Partial<User> = {
cards: [],
clerk_id: data.id,
display_name: `${data.first_name} ${data.last_name}`,
email: theEmail,
groups: [],
picture: data.profile_image_url || data.image_url,
username: data.username,
}
theUser = await mongo.insertUser(userDetails);
console.info("Create user %s completed", theEmail);
} else if (theUser) {
console.info("Get user %s completed", data.first_name);
} else if (theUser === undefined) {
throw new Error("Invalid Clerk event type")
}
setResponseStatus(event, 200)
return theUser;
} catch (error) {
let message = getMessage(error);
console.info("Could not find user %s because %s", theEmail, message);
setResponseStatus(event, 500, message);
}
});