-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy pathusers.ts
60 lines (54 loc) · 1.78 KB
/
users.ts
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { v } from "convex/values";
import { mutation, query } from "./_generated/server";
export const getUser = query({
args: {},
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity();
if (identity === null) {
return ("Not authenticated");
}
return identity
}
})
export const getUserByToken = query({
args: { tokenIdentifier: v.string() },
handler: async (ctx, args) => {
return await ctx.db
.query("users")
.withIndex("by_token", (q) =>
q.eq("tokenIdentifier", args.tokenIdentifier)
)
.unique();
},
});
export const store = mutation({
args: {},
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) {
throw new Error("Called storeUser without authentication present");
}
// Check if we've already stored this identity before
const user = await ctx.db
.query("users")
.withIndex("by_token", (q) =>
q.eq("tokenIdentifier", identity.subject)
)
.unique();
if (user !== null) {
// If we've seen this identity before but the name has changed, patch the value
if (user.name !== identity.name) {
await ctx.db.patch(user._id, { name: identity.name, email: identity.email });
}
return user._id;
}
// If it's a new identity, create a new User
return await ctx.db.insert("users", {
name: identity.name!,
email: identity.email!,
userId: identity.subject,
tokenIdentifier: identity.subject,
createdAt: new Date().toISOString(),
});
},
});