Initial commit: Kalendartool (Next.js, Prisma, Docker)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
58
app/api/me/profile/route.ts
Normal file
58
app/api/me/profile/route.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* GET /api/me/profile - aktuelles Profil (email, username, role).
|
||||
* PATCH /api/me/profile - Username aendern (oder loeschen).
|
||||
*
|
||||
* Der Username ist optional und eindeutig. Beim Setzen prueft der
|
||||
* Server das Format (Zod) und faengt Unique-Constraint-Verletzungen
|
||||
* (P2002) ab, um eine lesbare Fehlermeldung zurueckzugeben.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/db/client';
|
||||
import { requireDbUser } from '@/lib/api/context';
|
||||
import { updateUsernameSchema } from '@/lib/validation';
|
||||
import { errorResponse, validationErrorResponse } from '@/lib/api/responses';
|
||||
import { ZodError } from 'zod';
|
||||
|
||||
export async function GET(): Promise<NextResponse> {
|
||||
try {
|
||||
const user = await requireDbUser();
|
||||
|
||||
return NextResponse.json({
|
||||
user: { id: user.id, email: user.email, username: user.username, role: user.role },
|
||||
});
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(request: NextRequest): Promise<NextResponse> {
|
||||
try {
|
||||
const user = await requireDbUser();
|
||||
const body = updateUsernameSchema.parse(await request.json());
|
||||
|
||||
const updated = await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { username: body.username },
|
||||
select: { id: true, email: true, username: true, role: true },
|
||||
});
|
||||
|
||||
return NextResponse.json({ user: updated });
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
return validationErrorResponse(error);
|
||||
}
|
||||
// P2002 = Unique-Constraint-Verletzung (username bereits vergeben).
|
||||
if (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
(error as { code?: string }).code === 'P2002'
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Dieser Benutzername ist bereits vergeben.' },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user