-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathauth-user-emails.server.ts
More file actions
84 lines (71 loc) · 1.84 KB
/
Copy pathauth-user-emails.server.ts
File metadata and controls
84 lines (71 loc) · 1.84 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import 'server-only'
import { l, serializeErrorForLog } from '@/core/shared/clients/logger/logger'
import { supabaseAdmin } from '@/core/shared/clients/supabase/admin'
export type AuthUserEmailResolver = (
userIds: string[]
) => Promise<Map<string, string | null>>
export async function getAuthUserEmailsById(
userIds: string[]
): Promise<Map<string, string | null>> {
const uniqueUserIds = [...new Set(userIds.filter(Boolean))]
if (uniqueUserIds.length === 0) {
return new Map()
}
const { data, error } = await supabaseAdmin
.from('auth_users')
.select('id,email')
.in('id', uniqueUserIds)
if (error) {
throw error
}
return new Map(
data
?.filter((user) => user.id)
.map((user) => [user.id as string, user.email]) ?? []
)
}
export async function resolveCreatorEmails<
T extends {
createdBy?: { id: string; email?: string | null } | null
},
>(items: T[], resolveEmails: AuthUserEmailResolver): Promise<T[]> {
const creatorUserIds = items.flatMap((item) => {
const createdBy = item.createdBy
if (!createdBy) {
return []
}
return [createdBy.id]
})
if (creatorUserIds.length === 0) {
return items
}
let emailByUserId: Map<string, string | null>
try {
emailByUserId = await resolveEmails(creatorUserIds)
} catch (error) {
l.warn(
{
key: 'auth_user_emails:resolve_failed',
error: serializeErrorForLog(error),
context: {
userCount: new Set(creatorUserIds).size,
},
},
'Failed to resolve creator emails from Supabase Auth'
)
return items
}
return items.map((item) => {
const createdBy = item.createdBy
if (!createdBy) {
return item
}
return {
...item,
createdBy: {
...createdBy,
email: emailByUserId.get(createdBy.id) ?? null,
},
}
})
}