Newer
Older
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 { db } from '@/lib/db'
import { getCurrentUser } from '@/lib/session'
import { UsernameValidator } from '@/lib/validations/username'
import { z } from 'zod'
export async function PATCH(req: Request) {
try {
const session = await getCurrentUser()
if (!session) {
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.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 }
)
}
}