-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathpreferences.ts
43 lines (36 loc) · 1.13 KB
/
preferences.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
import { getServerSession } from 'next-auth'
import { prisma } from './prisma'
function generateUsernameWithRandomString(baseUsername: string): string {
const characters = 'abcdefghijklmnopqrstuvwxyz0123456789'
let randomString = ''
for (let i = 0; i < 6; i++) {
randomString += characters.charAt(
Math.floor(Math.random() * characters.length)
)
}
return `${baseUsername}_${randomString}`
}
export async function getUserPreferences() {
const session = (await getServerSession())!
if (!session?.user) return null!
const currentPreferences = await prisma.preferences.findFirst({
where: {
user_email: session.user!.email!
}
})
if (!currentPreferences) {
const initialUsername = generateUsernameWithRandomString(
session.user!.email!.split('@').at(0)?.toLowerCase()!
)
return await prisma.preferences.create({
data: {
user_email: session.user!.email!,
user_description: '',
user_fullname: session.user?.name ?? initialUsername,
user_profile_picture: session.user?.image!,
username: initialUsername
}
})
}
return currentPreferences
}