fix: wrap username change in try/catch and remove GET function
This commit is contained in:
parent
d2522c8d93
commit
50b402e5d9
2 changed files with 10 additions and 12 deletions
|
|
@ -10,13 +10,6 @@ const usernameSchema = z
|
||||||
.max(20, "Username cannot be more than 20 characters long")
|
.max(20, "Username cannot be more than 20 characters long")
|
||||||
.regex(/^[a-zA-Z0-9_]+$/, "Username can only contain letters, numbers, and underscores");
|
.regex(/^[a-zA-Z0-9_]+$/, "Username can only contain letters, numbers, and underscores");
|
||||||
|
|
||||||
export async function GET() {
|
|
||||||
const session = await auth();
|
|
||||||
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
||||||
|
|
||||||
return NextResponse.json({ username: session.user.username });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function PATCH(request: Request) {
|
export async function PATCH(request: Request) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
|
@ -30,10 +23,15 @@ export async function PATCH(request: Request) {
|
||||||
const existingUser = await prisma.user.findUnique({ where: { username } });
|
const existingUser = await prisma.user.findUnique({ where: { username } });
|
||||||
if (existingUser) return NextResponse.json({ error: "Username is already taken" }, { status: 400 });
|
if (existingUser) return NextResponse.json({ error: "Username is already taken" }, { status: 400 });
|
||||||
|
|
||||||
|
try {
|
||||||
await prisma.user.update({
|
await prisma.user.update({
|
||||||
where: { email: session.user?.email ?? undefined },
|
where: { email: session.user?.email ?? undefined },
|
||||||
data: { username },
|
data: { username },
|
||||||
});
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to update username:", error);
|
||||||
|
return NextResponse.json({ error: "Failed to update username" }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({ success: true });
|
return NextResponse.json({ success: true });
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import { redirect } from "next/navigation";
|
||||||
|
|
||||||
export default function UsernameForm() {
|
export default function UsernameForm() {
|
||||||
const [username, setUsername] = useState("");
|
const [username, setUsername] = useState("");
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState<string | undefined>(undefined);
|
||||||
|
|
||||||
const handleSubmit = async (event: FormEvent) => {
|
const handleSubmit = async (event: FormEvent) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue