-
Notifications
You must be signed in to change notification settings - Fork 267
/
route.ts
51 lines (42 loc) · 1.09 KB
/
route.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
import { getAuthSession } from '@/lib/auth'
import { db } from '@/lib/db'
import { UsernameValidator } from '@/lib/validators/username'
import { z } from 'zod'
export async function PATCH(req: Request) {
try {
const session = await getAuthSession()
if (!session?.user) {
return new Response('Unauthorized', { status: 401 })
}
const body = await req.json()
const { name } = UsernameValidator.parse(body)
// check if username is taken
const username = await db.user.findFirst({
where: {
username: name,
},
})
if (username) {
return new Response('Username is taken', { status: 409 })
}
// update username
await db.user.update({
where: {
id: session.user.id,
},
data: {
username: name,
},
})
return new Response('OK')
} catch (error) {
(error)
if (error instanceof z.ZodError) {
return new Response(error.message, { status: 400 })
}
return new Response(
'Could not update username at this time. Please try later',
{ status: 500 }
)
}
}